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?开发者_开发百科
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.
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.
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.
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.
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.
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?
精彩评论