Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay for constructors to throw runtime exceptions?

When checked exceptions are thrown from methods in a constructor that the constructor can't handle is it okay to catch them and throw them back out as a runtime exception if your sure the application can't handle it and will be useless without the object being constructed?

like image 708
insipid Avatar asked Feb 03 '10 18:02

insipid


People also ask

Is it OK to throw exception in 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.

Is it OK to throw runtime exception?

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 practice to throw exception in constructor C++?

Throwing exceptions from C++ constructors Since C++ constructors do not have a return type, it is not possible to use return codes. Therefore, the best practice is for constructors to throw an exception to signal failure. The throw statement can be used to throw an C++ exception and exit the constructor code.

Should we handle runtime exceptions?

Runtime exceptions represent problems that are a direct result of a programming problem, and as such shouldn't be caught since it can't be reasonably expected to recover from them or handle them. Catching Throwable will catch everything. This includes all errors, which aren't actually meant to be caught in any way.


1 Answers

Yes. This is standard practice.

In Effective Java, 2nd Ed. this is covered by Item 61, "Throw exceptions appropriate to the abstraction". Whether the resulting exception is checked or unchecked is a also covered by Effective Java in Item 58, "Use checked exceptions for recoverable conditions and runtime exceptions for programming errors".

That this is a constructor rather than a normal method isn't really an issue. (In fact, constructors arguably have more freedom as they are not bound by the super's interface.)

When throwing an exception as a result of another exception it's a good idea to ensure that you're setting the cause on the new exception.

like image 184
Laurence Gonsalves Avatar answered Oct 07 '22 13:10

Laurence Gonsalves