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.
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.
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.
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.
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.
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. :)
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