views:

92

answers:

3

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 pass the exception from the first catch block to the second, or do I have to duplicate the code?

+1  A: 

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.

Oded
+2  A: 

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?

Brian Rasmussen
Sadly (or possibly luckily) this isn't my code, so rewriting the Exception catch block isn't in my remit.At the moment the only "processing" is to display a MessageBox with the exception's Message so, for now, extracting it to its own method is probably overkill.
Rawling
In that case, it sounds like you should remove the general exception handling and let the exception bubble up to a catch all handler or simply let the application crash.
Brian Rasmussen
What I meant was, the general exception catch is correct according to the people who came before me, and it's not my place to try and rewrite it!Final fix: remove the specific exception catch block and simply check the type of the exception inside the general block. No code duplication, and makes more sense since we're looking for a specific exception, not a specific type of exception.
Rawling
+1  A: 

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.

M.A. Hanin
This is exactly what I want to do! Unfortunately, it seems C# doesn't support this.
Rawling