Reputation: 367
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)
{
...
}
Upvotes: 3
Views: 22647
Reputation: 86729
Do you mean that you want to throw a custom exception that isn't caught by the catch-all 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 stack 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 of why. I definitely suggest that rather than doing the above, you simply refactor so that you are no longer catching Exception
, which would be a far neater solution.
Upvotes: 6
Reputation: 2204
check this:
try
{
...
}
catch()
{
throw new Execption("I'M A NEW EXCEPTION")
}
finally
{
...
}
Upvotes: 1
Reputation: 1443
Try this
catch(OracleException ex)
{
throw new MyCustomException(
"MyCustomEX error: Unable to ......", ex);
}
Upvotes: 0
Reputation: 4051
Can't you simply add a catch
clause with your custom exception?
try
{
//Lots of code
}
catch (OracleException)
{
}
catch (MyCustomException)
{
}
catch (Exception)
{
}
Upvotes: -1