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?
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.
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.
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.
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.
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.
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