Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better to catch all exceptions except given types: catch and rethrow or catch when?

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?

like image 864
Ceshion Avatar asked Nov 16 '16 18:11

Ceshion


People also ask

Should you Rethrow an exception?

Upon determining that a catch block cannot sufficiently handle an exception, the exception should be rethrown using an empty throw statement.

When should you throw an exception or catch?

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.

Is it necessary to catch all types of exceptions?

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.

Why is catching all exceptions bad?

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.


1 Answers

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.

like image 180
Qrchack Avatar answered Sep 30 '22 08:09

Qrchack