Does it make sense to throw a private exception?
I want to throw a runtime exception in case my class invariants are invalidated. Since this is a programming error (similar to a NullPointerException), clients should not catch that exception.
Should the exception class be declared private or public (or something else)?
class Foo
{
// ...开发者_JS百科
private static class InvariantsViolated
{
// ...
}
}
Are there any guidelines on custom runtime exceptions and visibility?
You may consider using an existing exception unless you expect this exception to be caught in a different way. If it is not expected to be caught, I don't see the need for a custom exception. Some exceptions you could re-use
- AssertionError - To me this means there is an unrecoverable programming error of an indeterminate type.
- IllegalArgumentException - To me this means only of the arguments to the method was invalid.
- IllegalStateException - To me this means the state of the object (e.g. combination of values) is not valid for this operation.
If you want a custom exception you may consider extending these exceptions, or using one of the exceptions which extend these.
I believe that in order to throw
anything, that object has to implement the Throwable
interface, which meant that it has to be either an Error
or an Exception
. Since you don't want your clients to catch that event ever, you should probably use an Error
. From the Error
documentation:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.
That way you may avoid the dreaded Exception
catch-alls some programmers tend to use - most times these programmers don't even think about catching an Error
at all...
精彩评论