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
{
// ...
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
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...
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