Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is catching a RuntimeException not considered a good programming practice? [closed]

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?

like image 826
SPS Avatar asked Jun 21 '14 18:06

SPS


Video Answer


2 Answers

Throwable is super class of all Exception checked and unchecked(RuntimeException) and error.

java.lang.Object
     java.lang.Throwable
          java.lang.Exception
               java.lang.RuntimeException
          java.lang.Error

Ideally catching error is not a good practice.

And as RuntimeException extends Exception so it catches all RuntimeExcption's.

like image 92
Subhrajyoti Majumder Avatar answered Sep 29 '22 04:09

Subhrajyoti Majumder


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.

like image 41
Jon Skeet Avatar answered Sep 29 '22 02:09

Jon Skeet