c# – Why is it bad to catch all exceptions at once?

Question:

Is it anti-pattern to catch all exceptions at once?

Why this approach is bad:

try {
    foo();
} catch (Exception e) {
    // handle <-- разумеется, тут реальная обработка, а не подавление исключений
}

Without specifying what specific exceptions I want to handle.

Let's say I have code that works with the file system wrapped in try … catch, for specifics – copying a file .

The documentation contains as many as 8 exceptions that this method can throw – should a good programmer carefully write down all possible exceptions and periodically check that Microsoft does not add new ones?

I heard that you can generalize the exceptions and not write PathTooLongException , DirectoryNotFoundException and DirectoryNotFoundException every time, but handle the IOException once, from which they all inherit. This helps to reduce the number of catch blocks, but not much (in the example with File.Copy, it can be reduced by 4, for a total of 8). Is this the correct approach or does it have its own nuances too?

Answer:

You describe some very tiny rule and elevate it to the absolute. Fortunately, in nature there are no such rigid rules, and, when developing, the programmer, both in this case and in all other cases, should also use his head.

For example, the first question that may arise when handling an exception is – has the called method done its job? Or, if you are calling a third-party service on a timer, where would you like to throw an exception higher up? Is the calling code interested in the problem of the called function at all?

For example, if you are doing the same thing on a timer, it's just that a third-party service works and doesn't work, then it makes sense to write the fact of problems with it to the log and, perhaps, notify someone about problems, no matter what, the network has fallen off or the server returns 500 – the timer is not interested.

But if you are copying files, then, probably, the calling code will be interested to know about the result of the operation. In this case, if you catch all exceptions, then only in order to log and send the exception further, higher up the stack.

Regarding what types of exception catching is simple. If you have a difference between FileNotFoundException and DirectoryNotFoundException in your logic, then catch them with separate handlers. If there is no difference, and you are not interested in the specifics of the problem, only its presence, then intercept one.

Scroll to Top