ricki ricki - 3 years ago 108
C# Question

Throwing a custom exception inside try catch

If I have some code inside a big try catch which eventually catches an

OracleException
and a general
Exception
then I can't throw any custom exception inside the try catch can I, as it gets caught by the general
Exception
.

What am I supposed to do in this instance?

Thanks

try
{
// some code
if(a==b)
{
throw new MyCustomException(ex);
}
}
catch(OracleException ex)
{
...
}
catch(Exception ex)
{
...
}

Answer Source

Do you mean that you want to throw a custom exception that isn't caught by the catch-call Exception block?

If this is the case then try this:

try
{
    throw new MyCustomException();
}
catch (OracleException ex)
{
    // Handle me...
}
catch (MyCustomException)
{
    // Important: NOT `throw ex` (to preserve the stach trace)
    throw;
}
catch (Exception ex)
{
    // Handle me...
}

Any exception of type MyCustomException will be caught by the second catch (rather than by the 3rd catch) and then rethrown.

Note that it's generally bad practice to do catch (Exception) - this is a good example why. I definitely suggest that rather than do the above you simply refactor so that you are no longer catching Exception, which would be a far neater solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download