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.
Generic exceptions Error, RuntimeException, Throwable and Exception should never be thrown.
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.
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.
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.
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.
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