insipid
insipid

Reputation: 3308

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?

Upvotes: 20

Views: 4799

Answers (6)

relluf
relluf

Reputation: 109

Personally I hate to see constructors throw checked exceptions (as doppeldish already pointed out). Nevertheless, how can you be sure that the application can not handle the exception? Even if the application can't handle it, maybe the user can, by simply trying again?

Upvotes: 2

doppelfish
doppelfish

Reputation: 983

It's perfectly OK to throw a checked exception to indicate that construction of the object failed, as Chris Jester-Young commented already. Whether it is a good idea to throw an unchecked exception is another issue. You would loose the nagging of the compiler that urges you to catch and handle the exception, which you will certainly want to do.

Upvotes: 2

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143154

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.

Upvotes: 12

Cuga
Cuga

Reputation: 17904

Yes. Unless you know how the exception should be handled, you're better off throwing it, rather than simply swallowing it and printing out a stack trace (or worse, doing absolutely nothing).

This will help prevent some extremely difficult-to-debug errors later on.

Upvotes: 1

JonH
JonH

Reputation: 33143

Yes it is completly valid to throw the exception in your constructor. You have little or no other choice but to do this, especially when you are simply trying to construct an object and things just don't work out right.

Upvotes: 4

Robin
Robin

Reputation: 24262

Yes, this is inevitable in many constructors anyway when they call other methods since there is always a possibility that they will already throw unchecked exceptions.

Upvotes: 11

Related Questions