Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the Catch(Exception) almost always a bad Idea?

Why is the catch(Exception) almost always a bad Idea?

like image 645
Nasser Hadjloo Avatar asked Mar 10 '10 11:03

Nasser Hadjloo


People also ask

Why try catch is bad?

Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.

Why is it bad to throw exceptions?

Exceptions make it really easy to write code where an exception being thrown will break invariants and leave objects in an inconsistent state. They essentially force you to remember that most every statement you make can potentially throw, and handle that correctly. Doing so can be tricky and counter-intuitive.

Is catching runtime exceptions bad practice?

Additionally, catching RuntimeException is considered as a bad practice. And, thus, throwing Generic Exceptions/Throwable would lead the developer to catch the exception at a later stage which would eventually lead to further code smells.

Should exceptions always 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.


2 Answers

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 general principal is to catch the most specific type you can.

like image 169
anthares Avatar answered Oct 13 '22 19:10

anthares


Short story: it's called bug masking. If you have a piece of code which is not working well and throwing exceptions (or you pass malformed input to that piece of code) and you just blind your eyes by catching all possible exceptions, you will actually never uncover the bug and fix it.

like image 38
dimitarvp Avatar answered Oct 13 '22 18:10

dimitarvp