Pass exception from specific catch to less-specific catch
I am currently using two catch blocks after a try block. The first catches SqlExceptions, the second Exceptions. If the SqlException does not have a specific message, I want it to be handled by the general catch block. Is there any way I can p开发者_StackOverflowass the exception from the first catch block to the second, or do I have to duplicate the code?
First of all you should ask yourself if you really want to catch Exception
. If you cannot handle the exception, you shouldn't catch it.
If you do want to catch the all purpose exception and share some kind of processing between your catch blocks duplicating code is not the right approach imo. Why not encapsulate the processing in a method and call that from both blocks?
In this case, you will have to duplicate the code.
You can't bubble down the exception to a lower down catch block, though you could re-throw it in the exception block and let the calling function handle it.
Assuming the Catch statements aren't nested, this code works in VB.Net:
Try
SomeCode()
Catch ex As ArgumentException When ex.Message <> ""
Trace.WriteLine(String.Format("Caught argument exception with a message {0}", ex.Message))
Catch ex As Exception
Trace.WriteLine("Caught argument exception with no message, or some other type of exception")
End Try
if SomeCode throws an ArgumentExeption that has a message (like the ArgumentException created with the empty constructor), it will be handled by the first Catch statement. All other exceptions will be handled by the second Catch statement, including ArgumentException with an empty message.
I assume that if VB.NET can do it, C# can (but the assumption may be terribly wrong).
EDIT: It seems there is no equivelent code structure in C#, as asked here. Sorry if I was misleading.
精彩评论