Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you catch all exceptions? [closed]

Tags:

c#

This is not 'How To Catch All Exceptions' but rather 'Should You Catch All Exceptions'? In C# .NET I've noticed a tremendous amount of exceptions. Is it advisable to plan on catching every exception?

For example the DirectoryInfo() constructor throws 4 exceptions. Should I plan on catching these or only catch the ones that I can handle? Maybe let the others bubble up to Main() where I have a catch-all that then tells the user there is an uncaught exception. It just seems with all these possible exceptions your code could become more exception-handling than actual code.

like image 900
keelerjr12 Avatar asked Jun 25 '12 14:06

keelerjr12


People also ask

Which exceptions should be caught?

You should catch the exception when you are in the method that knows what to do. For example, forget about how it actually works for the moment, let's say you are writing a library for opening and reading files. Here, the programmer knows what to do, so they catch the exception and handle it.

Is it good practice to catch exception?

The short answer is NO. You would throw an exception if the application can't continue executing with the bad data. In your example, the logic is to display an error message on the front end and Option 2 is the cleaner method for achieving this requirement.

Why should I not wrap every block in try catch?

When you have methods that do multiple things you are multiplying the complexity, not adding it. In other words, a method that is wrapped in a try catch has two possible outcomes. You have the non-exception outcome and the exception outcome.

Is it OK to catch generic exception?

So in general, catching generic exceptions is bad unless you are 100% sure that you know exactly which kinds of exceptions will be thrown and under which circumstances. If in doubt, let them bubble up to the top level exception handler instead. A similar rule here is never throw exceptions of type System.


1 Answers

Only catch the ones that make sense to handle for the level of abstraction at which you are writing the code. Most exceptions will only be caught at a much higher level than where they are thrown.

So yes, you are correct. :)

like image 64
Matthew Watson Avatar answered Sep 17 '22 18:09

Matthew Watson