PHP exception Handling vs C# - c#

this is a really basic question (I hope). Most of the exception handling I have done has been with c#. In c# any code that errors out in a try catch block is dealt with by the catch code. For example
try
{
int divByZero=45/0;
}
catch(Exception ex)
{
errorCode.text=ex.message();
}
The error would be displayed in errorCode.text. If I were to try and run the same code in php however:
try{
$divByZero=45/0;
}
catch(Exception ex)
{
echo ex->getMessage();
}
The catch code is not run. Based on my limeted understanding, php needs a throw. Doesn't that defeat the entire purpose of error checking? Doesn't this reduce a try catch to an if then statement?
if(dividing by zero)throw error
Please tell me that I don't have to anticipate every possible error in a try catch with a throw. If I do, is there anyway to make php's error handling behave more like c#?

You could also convert all your php errors with set_error_handler() and ErrorException into exceptions:
function exception_error_handler($errno, $errstr, $errfile, $errline )
{
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
try {
$a = 1 / 0;
} catch (ErrorException $e) {
echo $e->getMessage();
}

PHP's try-catch was implemented later in the language's life, and so it only applies to user-defined exceptions.
If you really want to handle actual errors, set your own error handler.
To define and catch exceptions:
function oops($a)
{
if (!$a) {
throw new Exception('empty variable');
}
return "oops, $a";
}
try {
print oops($b);
} catch (Exception $e) {
print "Error occurred: " . $e->getMessage();
}

From http://php.net/manual/en/language.exceptions.php
"Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException."
See also http://www.php.net/manual/en/class.errorexception.php

I think the only way to deal with this in PHP is to write:
try
{
if ($b == 0) throw new Exception('Division by zero.');
$divByZero = $a / $b;
}
catch(Exception ex)
{
echo ex->getMessage();
}
Unlike in C#, not every issue will raise an exception in PHP. Some issues are silently ignored (or not silently - they print something to the output), but there are other ways to handle these. I suppose this is because exceptions were not a part of the language since the first version, so there are some "legacy" mechanisms.

Related

How can I catch a specific kind of InvalidOperationException? [duplicate]

Does C# support compiling filters? How do filters even work or what do they do?
Like reflector decompiles a filter as
try
{
}
catch(Exception e) when (?)
{
}
Since C# 6 you can now do this.
try { … }
catch (MyException e) when (myfilter(e))
{
…
}
This is different from using an if statement from within the catch block, using exception filters will not unwind the stack.
C# did not support exception filters like VB does until C# 6. As for how they work, see Eric Lippert's "Finally" Does Not Mean "Immediately"
Starting in C# 6, exception filters are supported, as the C# FAQ demonstrates:
try { … }
catch (MyException e) when (myfilter(e))
{
…
}
If the parenthesized expression after ‘if’ [now when] evaluates to true, the catch block is run, otherwise the exception keeps going.
Exception filters are preferable to catching and rethrowing because they leave the stack unharmed. If the exception later causes the stack to be dumped, you can see where it originally came from, rather than just the last place it was rethrown.
It is also a common and accepted form of “abuse” to use exception filters for side effects; e.g. logging. They can inspect an exception “flying by” without intercepting its course. In those cases, the filter will often be a call to a false-returning helper function which executes the side effects:
private static bool Log(Exception e) { /* log it */ ; return false; }
…
try { … }
catch (Exception e) when (Log(e)) {}
Thanks to Mafii for the link to the C# 6 documentation.
Exception filters support in C# is introduced in C# 6 (Visual Studio "Dev14"):
try
{
throw new ApplicationException("1");
}
catch (ApplicationException ex) when (ex.Message == "2")
{
// this one won't execute.
}
catch (ApplicationException ex) when (ex.Message == "1")
{
// this one will execute
}
While catching exceptions, if you want to handle the exceptions differently then you can use Exception Filter
-- After C# 6.0
-- After VB 7.1 Using WHEN
1) C# Sample After C# 6.0
try
{
throw new CustomException { Severity = 100 };
}
catch (CustomException ex) when (ex.Severity > 50)
{
Console.WriteLine("*BING BING* WARNING *BING BING*");
}
catch (CustomException ex)
{
Console.WriteLine("Whooops!");
}
Note : Keep in mind that the order matters
2) C# Sample Before C# 6.0
try
{
throw new CustomException { Severity = 100 };
}
catch (CustomException ex)
{
if (ex.Severity > 50)
{
Console.WriteLine("*BING BING* WARNING *BING BING*");
}
else
{
Console.WriteLine("Whooops!");
}
}
Since this piece of code is equivalent to the previous one. means, they are equivalent, right? --- "But No they are not equivalent"
NOTE : exception filters don’t unwind the stack
Read it more from Here

How should I handle unapproriate situations in C#

I'm a beginner and haven't had a job yet, so I never work experience with code.
My question is:
How should I handle situations, when user enters a value, that doesn't throw exception, but is unacceptable and and program should be closed.
Should I throw an exception with some message in catch block, or it would be enough to just show a message ?
Its really up to the requirements of the application that you are developing. But c# has a specific exception type for this:
InvalidArgumentException
And you can use it like this:
if (!ValidateUserInput(input))
throw new InvalidArgumentException ("input is invalid");
You can then catch that further up in the application and decide how to handle it
It all depends of You. Depends on what You want to achieve.
There is no ultimate answer to this.
It is good to do everything You said. Throw exeption in try catch block and then give a information for user and close program.
Additionally log the error with more informataion to a file or databases.
Message box is good, because is user firendly.
Throw exeption is also good because is very readable for developer - when they read You code they see this is a bad sitiation.
For example what to do:
try
{
if (IsErrorValidation())
{
throw new Exeption("You input wrong data");
}
}
catch (Exception e)
{
MessageBox.Show("Error" + e.Message );
CloseProgram();
}
You create new Exception with Your massage.
Better is create Your own type of Exeption for example ErrorValidationException or use the predefined InvalidArgumentException which exist in C#
try
{
if (IsErrorValidation())
{
throw new ErrorValidationException("You input wrong data");
}
}
catch (ErrorValidationException e)
{
MessageBox.Show("Error" + e.Message);
CloseProgram();
}
catch (Exeption e)
{
...
}
Then You can use this type of exception later and You can serve this type of exception in a different way

Is multiple try-catch in error sensitive code considered a good practice?

I have a code segment that is responsible for orchestrating the execution of a few modules and it is very sensitive to errors - I want to make sure I log and alert about every exception that occurs.
Right now I have something like this:
try
{
ModuleAResult aResult = ModuleA.DoSomethingA();
}
catch (Exception ex)
{
string errorMessage = string.Format("Module A failed doing it's thing. Specific exception: {0}", ex.Message);
// Log exception, send alerts, etc.
}
try
{
ModuleBResult bResult = ModuleB.DoSomethingB();
}
catch (Exception ex)
{
string errorMessage = string.Format("Module B failed doing it's thing. Specific exception: {0}", ex.Message);
// Log exception, send alerts, etc.
}
// etc for other modules.
It looks to me that the multiple try-catch is making this segment less readable. Is it indeed the right thing to do?
Yes, it's the right thing.
But you should have the performance in in mind, maybe it's better to put all method calls in one try/catch and add stack trace and error information in the exception in the methiod itself.
public void ModuleA.DoSomethingA()
{
throw new Exception("Error in module A");
}
try
{
ModuleAResult aResult = ModuleA.DoSomethingA();
ModuleBResult bResult = ModuleB.DoSomethingB();
}
catch (Exception ex)
{
// get information about exception in the error message
}
You did well.
This way, you can process the error after each module. If you want to run it all and then do error handling, consider this alternative:
try
{
ModuleAResult aResult = ModuleA.DoSomethingA();
ModuleBResult bResult = ModuleB.DoSomethingB();
}
catch(ModuleAException ex)
{
// handle specific error
}
catch(ModuleBException ex)
{
// handle other specific error
}
catch (Exception ex)
{
// handle all other errors, do logging, etc.
}
i think that depends on the approach that you want to follow.
It seems like you error messsages are different for each module that raises exception so i guess the approach that you followed is right.
you could have put the whole thing in a big try - catch block then in that case you will not know which module caused the exception as a generic excpetion gets printed.
try
{
ModuleAResult aResult = ModuleA.DoSomethingA();
ModuleBResult bResult = ModuleB.DoSomethingB();
}
catch (Exception ex)
{
string errorMessage = string.Format("Either Module A or B failed", ex.Message);
// Log exception, send alerts, etc.
}
So if you want your exception handling to not be cleaner use the above code.
Otherwise what you followed is absolutely fine.

Is this try-catch block valid?

Newby question...
Is it valid to do:
try
{
// code which may fail
}
catch
{
Console.Writeline("Some message");
}
Or do I always have to use:
try
{
// code which may fail
}
catch (Exception e)
{
Console.Writeline("Some message");
}
Both blocks are valid.
The first will not have an exception variable.
If you are not going to do anything with the exception variable but still want to catch specific exceptions, you can also do:
try
{
// your code here
}
catch(SpecificException)
{
// do something - perhaps you know the exception is benign
}
However, for readability I would go with the second option and use the exception variable. One of the worst things to do with exceptions is swallow them silently - at the minimum, log the exception.
Yep, absolutely, such a catch block called general catch clause, see more interesting details in the C# Language Specification 4.0, 8.10 The try statement:
A catch clause that specifies neither an exception type nor an
exception variable name is called a general catch clause. A try
statement can only have one general catch clause, and if one is
present it must be the last catch clause
Yes, your first block of code valid. It will catch all exceptions.
It is. It will catch all the exception. So the two code examples do the same.
First one is valid, and it acts just like the second one.
http://msdn.microsoft.com/en-us/library/0yd65esw%28v=vs.80%29.aspx
The catch clause can be used without arguments, in which case it
catches any type of exception, and referred to as the general catch
clause. It can also take an object argument derived from
System.Exception, in which case it handles a specific exception.
Yes it is valid.
you can always refer to this article:
Best Practices for Handling Exceptions on MSDN
Of course it is valid, you specify catch(Exception e) when you want to output the error message ex.Message, or to catch a custom or a concrete Exception. Use catch in your situation.
As #David answered this is valid.
You could use second syntax if you want to get more infos or catch a specific exception.
E.g.
catch (Exception e)
{
Debug.Print(e.Message);
}
catch (Exception e)
{
Console.Writeline("Some message");
}
In this block you can use SqlException, etc..
catch (SqlException e)
{
Console.Writeline("Some message");
}
For this use the "(SqlException e)"
If you will use a generic menssage, use this:
catch
{
Console.Writeline("Some message");
}
or
catch (Exception)
{
Console.Writeline("Some message");
}
Don't forget that you can chain catch your exceptions. This will allow you to handle different scenarios based upon the exception(s) the code may throw.
try
{
//Your code.
}
catch(SpecificException specificException)
{
//Handle the SpecificException
}
catch(AnotherSpecificException anotherSpecificException)
{
//Handle AnotherSpecificException
}
catch(Exception exception)
{
//Handle any Exception
}

Exception Handling

Is there a way in C# to catch any kind of exception?
Like in C++ to catch any kind of exception
the format is like
try{
//Statements
}
catch(...){
// Some more statements
}
But this format in c# fails.
Help?
You can catch anything like :
catch {}
From .NET 2 and further, this is equivalent to:
catch(Exception ex) {}
Because every exception (even a Windows SEH exception) is guaranteed to be derived from System.Exception.
Check this link out. It's all about exceptions.
What you are trying to do is use a parameter-less catch like this:
try {
// your code
} catch {
// any exception
}
try {
// Statements
} catch (Exception ex) {
// Do stuff with ex
}
That should work.
catch(Exception ex)
or catch() <-- i believe the second one works
The .NET framework provides a mechanism to detect/handle run time errors. C# uses three keywords in exception handling: try, catch, finally. The try block contains the statement that can cause an exception. The catch block handles the exception, and the finally block is used for cleaning up.
try
{
//statements that can cause an exception
}
catch(Type x)
{
//statements for handling an exception
}
finally
{
//cleanup code
}

Categories

Resources