views:

294

answers:

6

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?

+7  A: 

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.

Robin
This is a good point.
insipid
+2  A: 

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.

JonH
For clarification, are you saying its okay to convert to an unchecked exception. Or do you mean just adding a throws clause?
insipid
I frequently would throw `IllegalArgumentException` with a string describing it.
philfreo
A: 

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.

Cuga
+6  A: 

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.

Laurence Gonsalves
+1 for good source
insipid
+1  A: 

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.

doppelfish
+1  A: 

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?

relluf
+1 something to consider :P thanks
insipid