Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Exception take Throwable as a constructor parameter instead of Exception?

I noticed recently that Exception has several constructors which take Throwable as a parameter. Throwable has two subclasses, Error and Exception, and generally all documentation indicates that you should not attempt to catch or handle an Error. Therefore, I am curious why Exception takes a Throwable as a constructor parameter instead of an Exception. This implies that an Exception could be created with an Error as its cause and could be handled by the application. Why is this the case?

Should custom Exception classes then only provide constructors that take Exception as parameters?

like image 999
Sam Eberspacher Avatar asked May 04 '16 17:05

Sam Eberspacher


People also ask

Should exceptions be thrown in the constructor?

The short answer to the question “can a constructor throw an exception in Java” is yes! Of course, properly implementing exceptions in your constructors is essential to getting the best results and optimizing your code.

What happens when exception is throw in constructor?

When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.

Is it a good practice to catch throwable instead of exception?

Don't Catch Throwable You can use it in a catch clause, but you should never do it! If you use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application.

Is throwing exception from constructor accepted as a good practice?

Throwing exceptions in a constructor is not bad practice. In fact, it is the only reasonable way for a constructor to indicate that there is a problem; e.g. that the parameters are invalid.


1 Answers

I guess it's basically because:

  1. it's not recommended to handle an Error but it's not forbidden.

  2. it's a good practice to program to the interface anyway, so the parameter type should support the widest range of types by having it as the root interface Throwable.

like image 86
M A Avatar answered Oct 10 '22 03:10

M A