Why is catching a RuntimeException not considered a good programming practice?

Why is catching a RuntimeException using catch(Throwable exc) {} not considered a good programming practice? What is the right way to handle RuntimeExceptions?

Also, why does catch(Exception exc) {} not catch RuntimeException? How is this behavior implemented?

Jon Skeet
people
quotationmark

Usually, a RuntimeException indicates a programming error (in which case you can't "handle" it, because if you knew to expect it you'd have avoided the error).

Catching any of these general exceptions (including Throwable) is a bad idea because it means you're claiming that you understand every situation which can go wrong, and you can continue on despite that. It's sometimes appropriate to catch Exception (but not usually Throwable) at the top level of the stack, e.g. in a web server - because usually whatever's gone wrong with a single request, you normally want to keep the server up and responding to further requests. I don't normally catch Throwable, as that includes Error subclasses which are normally used to indicate truly catastrophic errors which would usually be best "handled" by terminating the process.

Fundamentally, when there's an error you need to be very cautious about continuing with a particular task - you need to really have a pretty good idea about what the error means, as otherwise you could go ahead with a mistaken assumption about the state of the world, and make things worse. In most cases (not all), simply giving up on a request is better than trying to carry on regardless of a mysterious failure. (It does very much depend on context though - you might not care what went wrong when trying to fetch one piece of secondary information, for example.)

As for catching Exception not catching RuntimeException - that's simply not true. The only odd thing about RuntimeException is that it (and subclasses) are unchecked exceptions, whereas Exception and all other subclasses of Exception are checked.

people

See more on this question at Stackoverflow