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?
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.
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.
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.
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.
I guess it's basically because:
it's not recommended to handle an Error
but it's not forbidden.
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
.
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