Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing generic Exception discouraged?

Tags:

java

exception

Why is it discouraged to throw a generic (java.lang.Exception) exception, when it is usually sufficient to handle most conditional failures within a method? I understand that if a method could throw multiple types of exceptions then throwing specific subclasses of an exception might clarify the handling a bit, but in a general fail/succeed case I think Exception serves more than adequate.

like image 268
oldSkool Avatar asked Oct 31 '11 20:10

oldSkool


People also ask

Should I throw generic exception?

Generic exceptions Error, RuntimeException, Throwable and Exception should never be thrown.

Is throwing runtime exception good practice?

Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.

Is it good to use printStackTrace?

The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred. printStackTrace() is very useful in diagnosing exceptions.


2 Answers

The problem is that Exception is also the superclass of RuntimeException, which encompasses some stuff that shouldn't be caught as it indicates a problem with the programming rather than an exceptional condition that arises from context. You don't want to catch a BufferOverflowException or UnsupportedOperationException under normal circumstances. Besides, throwing separate Exception types gives the calling code control over how to handle each one. Boilerplate is reduced in Java 7 with the new multi-catch feature.

like image 159
G_H Avatar answered Oct 21 '22 08:10

G_H


If you throw more specific exceptions, that does not stop any calling code from dealing with all of them in one Exception catch block. Being more specific is more documenting as to what type of errors occur, making it easier for programmers to deal with them separately.

Additionally, by throwing "Exception" itself you're basically telling callers of your code that they can't rule out any class of exception. An IOException might occur, as might a NumberFormatException, etc.

like image 30
Mark Peters Avatar answered Oct 21 '22 08:10

Mark Peters