This exception handling code requires fixing - c#

This is my current exception handling code.
Take especial note of the line throw e; marked with ***.
try
{
//some code that could cause exception
}
catch (FaultException e) //first catch a particular type of exception only
{
if (Regex.IsMatch(e.Message, "something")) //satisfying a particular condition
{
Console.WriteLine("Particular exception occurred.");
return;
}
else
throw e; // <-- *** Problem! Not getting caught by the "catch" below.
}
catch (Exception e) //catch all other exceptions
{
Console.WriteLine("General exception ocurred");
return;
}
The problem is this: If the throw e; // <-- *** occurs, it is not getting caught by the final catch. Instead, the app just crashes as if the exception was not handled.
How can this be fixed in the simplest possible way?
You see in the first catch that I'm only interested in actually handling FaultException exceptions satisfying a particular condition, but leave all others (both FaultException exceptions not satisfying the condition and exceptions that are not FaultException) to the final catch. Unfortunately, this is not working properly.
I'm on .NET 4.

You don't fully understand the try/catch syntax. You can attach multiple catches to a single try - the one that matches most closely is the one that will be selected. In this case, FaultException's catch will fire, and then the more general Exception one will never be called, because the exception has already been handled.
What you need to do is wrap the entire try/catch in another try/catch specifically for the more general Exception case, if you always want to handle that; either that or rework your logic. (For instance, you could just simplify it to be an Exception catch and then check if it's a FaultException.)

Only one catch block is executed per try block.
I would rewrite the catch block as:
catch (Exception e)
{
if (e is FaultException && Regex.IsMatch(e.Message, "something"))
{
....
}
else // all other exceptions
{
....
}
}

The throw e will never be caught by exception catches at the same level.
A throw inside of a catch, will always throw to the invoker of the method.
Also, its recommended that if you want to re-throw do throw instead of throw e. The first case preserves the call-stack.

If you throw an exception within a catch block, it won't be caught within the same try-catch.
You could repeat in the else condition what you're doing in the other catch block (not too bad in this specific case).

Related

Difference between parameterless catch and other catch

I have there piece of code
//Code 1 Code 2 Code 3
try try try
{ { {
//Exp occur //Exp occur //Exp occur
} } }
catch (Exception e) catch (Exception) catch
{ { {
//Handle exp //Handle exp //Handle exp
} } }
What is the difference between all of three codes
P.S. I'm new to C# and as far as Java or Objective-C is concerned this syntax throws error
Code 1
Its catching Exception in an object e which can be later used for exception handling. For example you can log the Message property or view stack trace using e.Message or e.StackTrace
Code 2
You are catching all the exception of the base type Exception but since you don't have any object related to it, you can only throw that exception so that it can bubble up or you may ignore the exception. If in that code you had :
catch(InvalidCastException)
Then all the InvalidCastException will be handled in the block without the exception object
Code 3
You are catching all type of exceptions irrespective of their type, which is similar to your code 2 with base class Exception
try-catch - MSDN
Although the catch clause can be used without arguments to catch any
type of exception, this usage is not recommended. In general, you
should only catch those exceptions that you know how to recover from.
Its always better if you catch specific exceptions before catching the base one. Something like.
try
{
}
catch(InvalidCastException ex)
{
}
catch(Exception ex)
{
}
try - catch - MSDN
It is possible to use more than one specific catch clause in the same
try-catch statement. In this case, the order of the catch clauses is
important because the catch clauses are examined in order. Catch the
more specific exceptions before the less specific ones. The compiler
produces an error if you order your catch blocks so that a later block
can never be reached.
Code 1 - fairly normal catch, hopefully doesn't need explanation
Code 2 - You want to execute a particular piece of code when a particular exception occurs, but you have no intention of actually interacting with the exception object. Should almost always have a throw; statement at the end, so that someone else higher up the stack who does care can catch it.
Code 3 - You want the code to execute for any exception(*) (except for any caught by earlier catch clauses of the same try). Again, should almost always include a throw; so that higher code can catch and actually process the exception.
At some level (possibly just at the top level, in the unhandled exception handlers for whatever environment you're in), something ought to be inspecting the exception object and probably logging it (if possible).
Here if you want to use the variable 'e' for getting the Exception message, Line or type.
//Code 1
try
{
//Exp occur
}
catch (Exception e)
{
//Handle exp
}
Below code for getting particular type of Exception and not dealing with Exception variable.
//Code 2
try
{
//Exp occur
}
catch (Exception)
{
//Handle exp
}
Below code catching all types of exceptions.
//Code 3
try
{
//Exp occur
}
catch
{
//Handle exp
}
if you plan to actually use the exception object, to log its properties to a log file or to show a message box or to throw another kind of exception and pass the current exception to its constructor, then you must use the first of the three (most left one).
in general the most used approach is the first one anyway, if you want to handle different kind of exceptions separately you can have multiple catch blocks starting with the most specialized on top and have the one you wrote at the bottom so that all exceptions not already handled will end in the generic catch block.
Nothing. They all catch EVERY exception that could possibly occur (by catching base type Exception or just any). This is typically frowned upon, for good reason. You should catch specific exceptions in the order you expect, and then if you do want to catch all exceptions catch Exception at the end.
try
{
}
catch (MyCustomException)
{
// do something for your custom exception
}
catch (Exception)
{
// do something for everything else
}
When you specify a variable for your exception such as catch (Exception e) you will have access to the stack trace (and other exception information) via e.Property or simply e.ToString() for the full message. It's also best practice to throw the exception when caught (well, unless you want to suppress it at this level and not allow your calling code to see the exception) so it bubbles up and you preserve the stack trace:
catch (Exception e)
{
// do something with e
throw;
}
Code 1 catches every exception (in your case!) and declares it, so you can use it later e.g. for Error-Messages.
MessageBox.Show(e.Message);
Code 2 also catches every exception (in your case!), but you can't use it, because it is not declared.
These two methods are not designed for that, they're designed to catch specific or custom exceptions.
try
{
//mycode
}catch(MyException myExc)
{
//TODO HERE
Console.Write(myExc.Message);
}
The third one catches all exceptions. Because there is no definition.
Take a look at: http://msdn.microsoft.com/de-de/library/0yd65esw%28v=vs.80%29.aspx
to learn more about exceptions in C#.
Differences:
Declaring Exception Parameter ex allows you to access the Exception object, in order to see and work with its properties, fields, methods and the like. This "ex" variable works like any parameter in any method.
Declaring Exception Type without parameter ex allows you to separate several "catch" areas for different types of exception. It is useless, and functionally equivalent to code sample 3 as you define it here, but if you need to do different actions depending on the type of the exception, and you do not need to access the exception object (you only need to know the type of the exception), then this is your way to go.
Untyped Catch Exception Handler allows you to add a fallback for any Exception that might be thrown, whatever its type. Since it is not parameterized, however, you won't have access to the Exception object's properties or methods. Both code sample 2 and code sample 3 therefore are equivalent.
Example:
try{ // code that throws exception }
catch(TypeException ex)
{
// code to handle exceptions of type TypeException
// I can access ex parameter, for example to show its Message property
MessageBox.Show(ex.Message);
}
catch(OtherTypeException)
{
// code to handle exceptions of type OtherTypeException
// I cannot access the ex parameter since it is not declared, but I know
// the exact type of the exception
MessageBox.Show("There was an exception of Other Type");
}
catch
{
// code to handle any other exception
// this is functionally equivalent to catch(Exception) since all typed exceptions
// inherit from the base type Exception
MessageBox.Show("An unknown exception has been thrown.");
}
...

To throw or not to throw an exception in C# [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why catch and rethrow Exception in C#?
I've been scouring the net trying to find the answer to this question - What's the between the two?
try
{
//Do Something
}
catch
{
throw;
}
vs
try
{
//Do Something
}
catch
{
}
or
try
{
//Do Something
}
catch (Exception Ex)
{
//Do something with Exception Ex
}
The first one rethrows the exception up the stack and preserves the stack trace.
The second one swallows (hides) the exception.
The third one probably also swallows the exception but it depends on what (//Do something) does.
catch --> throw will actually just throw your error, so you will have to catch it somewhere else. This can be useful if you want to catch something first and then throw the error to other methods above.
Example:
try
{
// do something
}
catch
{
Console.WriteLine("Something went wrong, and you'll know it");
throw;
}
// won't get here anymore, the exception was thrown.
While try --> catch will just let you ignore the error.
try
{
// do something
}
catch
{
Console.WriteLine("Something went wrong, and you won't know it.");
}
// continuing happily
The first one re-throws the same exception that was caught. the second one swallows the exception as if it never happened. So it depends on what you need.
Please note that there IS a difference between these two:
try
{
//Do Something
}
catch (Exception Ex)
{
//re-throws the same exception that was caught
throw;
}
try
{
//Do Something
}
catch (Exception Ex)
{
//throws a _new_ exception containing Ex
throw Ex;
}
In the first, you are just rethrowing the exception. You don't need try/catch in this case, because you aren't doing anything with the caught exception.
In the second, you are swallowing all exceptions. This is incredibly dangerous. Do not ever do this. It is never correct.
In the last, you haven't given us enough detail to know. You are catching the exception, and you might do something with it. You could rethrow, you could swallow. You haven't told us.
In the first block, an exception is thrown again inside of the handler for the first block. That means that it can be picked up by an outer-try/catch scope block. The second block "eats" the exception in the catch block, and program execution can continue normally after the code in the catch block is executed.
In the first case the exception is rethrown to the caller. This version is pointless because you do nothing with the exception but in practice you may do something and then throw the exception to the caller. It is also useful when filtering exceptions for example
try
{
//do somethign
}
catch(Exception1)
{
throw;
}
catch
{
//do something
}
The second is something you should never do. You are covering an exception and making it harder to catch eventual bug in your application. You either need to handle the exception in a meaningful way or let it break the program (or let the caller handle it)
The third example is simple exception handing. Make sure you don't use it as a form of if/else (flow control)

Exception catching

What is the difference between
try
{
...
}
catch (NHibernate.ADOException exception)
{}
and
try
{
...
}
catch (exception ex)
{}
In the catch block you specify which exceptions you wish to catch. So if you have
try {}
catch(Exception e){}
it will catch all exceptions that derive from the Exception class (so ALL exceptions). If you have:
try{}
catch (NHibernate.ADOException exception){}
it will only catch exceptions that are or derive from ADOException. So if you get an ArgumentException, it will pass through as if there were no try/catch.
I'm assuming you meant
catch (Exception ex) {}
with the second snippet.
Then the difference is that the first one will only catch one specific type of exception, namely NHibernate.ADOException while the second one will enter the catch block for all exceptions that could possibly be thrown.
The second is usually bad practice since you're claiming to handle every conceivable type of error. However, it can make sense in the outermost scope as a catch-all for any exception that got through.
Using catch { Exception } is strongly not recommended, because this actually hides a bugs. In every place where exception may be thrown, it is necessary to catch only expected exception types, even if this requires to write more code lines. When unexpected exception is thrown, program must crash, this is the only way to fix the bug.

What does "throw;" by itself do? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
difference between throw and throw new Exception()
What would be the point of just having
catch (Exception)
{
throw;
}
What does this do?
By itself, the throw keyword simply re-raises the exception caught by the catch statement above. This is handy if you want to do some rudimentary exception handling (perhaps a compensating action like rolling back a transaction) and then rethrow the exception to the calling method.
This method has one significant advantage over catching the exception in a variable and throwing that instance: It preserves the original call stack. If you catch (Exception ex) and then throw ex, your call stack will only start at that throw statement and you lose the method/line of the original error.
Sometimes you might want to do something like this:
try
{
// do some stuff that could cause SomeCustomException to happen, as
// well as other exceptions
}
catch (SomeCustomException)
{
// this is here so we don't double wrap the exception, since
// we know the exception is already SomeCustomException
throw;
}
catch (Exception e)
{
// we got some other exception, but we want all exceptions
// thrown from this method to be SomeCustomException, so we wrap
// it
throw new SomeCustomException("An error occurred saving the widget", e);
}
It rethrows the exact same error, you gain nothing by this.
Sometimes you can use the catch method to do some logging or something without interupting your exception like this:
catch (Exception) {
myLogger.Log(LogLevels.Exception, "oh noes!")
throw;
}
I initially mistakingly thought this would unwind your stack, but this would only be if you would do the following:
catch (Exception err) {
throw err;
}
Only reason I can think of is if you want to put a breakpoint there during debugging.
It's also the default code being generated by some tools I think.
Simply rethrow the current exception, and that exception will keep its "source" and the stack trace.

Unexpected value in Exception object in catch block (c# compact framework)

I maintain a c# compact framework application and have had 2 cases in 2 days where the a caught exception had a unexpected string in the Message. Both times due to a different exception type being thrown. In the following code the socket exception is caught, but the message shown relates to something else.
//method1
try
{
soc.Connect(new IPEndPoint(IPAddress.Parse(_serverAddress), _serverPort));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message)
}
//method2
try
{
m_socServer.Connect(new IPEndPoint(IPAddress.Parse(_serverAddress), _serverPort));
}
catch (SocketException sex)
{
MessageBox.Show(sex.Message)
}
In 'method1' the exception is thrown upon fail to connect, the catch block entered, but the message box shown an exception I know is from outside of this try block. In 'method2' the exception is caught and the message is correct. These two try catch blocks are the only thing changed in the code.
I have yet to reproduce this in a small test program, but the program I maintain has this behaviour.
Where and why does 'method1' not get the unexpected value?
You are probably mistaken - in these 2 cases, some other exception (the one you're receiving) is being thrown instead of a SocketException.
If you're only expecting SocketException to be thrown, you should only provide a handler for that case. Other exceptions, in this situation, are probably truly exceptional - meaning that you aren't going to be able to correctly recover.
In that case, it's usually better to not handle the exception, and let it bubble up. If you feel that this is incorrect, put in the SocketException handler AND a generic exception handler, and make sure to check your stack traces (and potentially InnerException properties) in the exceptions:
try
{
//throw SocketException
}
catch (SocketException sockEx)
{
MessageBox.Show(sockEx.Message)
}
catch (Exception ex)
{
MessageBox.Show(ex.Message)
}
The statement you have above will catch ALL Exceptions, not just a specific type of exception.
If you want to handle specific exception types, you need to have code similar to this:
try
{
// Do some work.
}
catch(SocketException ex)
{
// Handle a known SocketException
}
catch(NullReferenceException ex)
{
// Handle a known NullReferenceException
}
catch(OtherSpecificException ex)
{
// You get the idea
}
catch(Exception ex)
{
// This will be everything else you haven't explicitly caught.
// It will also give you the most generic details about the Exception.
}
When you handle exceptions you can think of who needs to be notified of the error: the user? or the admin/developer?
You can define that a SocketException contains a message that the user needs to be notified of, and every other exception should be saved for developers or administrators to see. For example you can write the full exception to a file, or event you can have a special MessageBox. "Unexpected Error, please notify the administrator: " + ex.ToString().
Make sure you write the whole ex.ToString() because it includes the stacktrace and all InnerException's.
The best practice is to keep the catch(Exception ex) on the outer level of your application so you handle all unexpected exception in one place.

Categories

Resources