If I wanted to catch all exceptions except for given types, and those specific types would be re-thrown to be caught in a higher context, would it be better to do:
try
{
//Code that might throw an exception
}
//Catch exceptions to be handled in this context
catch (Exception ex) when (!IsExcludedException(ex))
{
//Handle leftover exceptions
}
Or would it be better to do:
try
{
//Code that might throw an exception
}
catch (SpecificException)
{
throw;
}
//Catch exceptions to be handled in this context
catch (Exception ex)
{
//Handle leftover exceptions
}
Or does it not really matter? Is there a better way?
Upon determining that a catch block cannot sufficiently handle an exception, the exception should be rethrown using an empty throw statement.
You generally throws an exception when you want to notify the caller of the method of some failures. Save this answer. Show activity on this post. As others have said, as a general rule, you should catch an exception when you can actually handle it, otherwise, just throw it.
It's not absolutely required to have a try/catch block for your exceptions. Instead, you can throw them to someone who is able to handle the exception properly. There are 2 kinds of exceptions: Checked and Unchecked.
Because when you catch exception you're supposed to handle it properly. And you cannot expect to handle all kind of exceptions in your code. Also when you catch all exceptions, you may get an exception that cannot deal with and prevent code that is upper in the stack to handle it properly.
The second way is definitely cleaner to analyse and it's what I see the most. The specific catch happens first and doesn't trigger the generic one, but you still have a fallback if you didn't implement a specific one. Also, for handling more than one specific exception you'd need more !(ex is SpecificException)
checks as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With