6

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?

fredoverflow
  • 237,063
  • 85
  • 359
  • 638

2 Answers2

3

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.

Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075
  • I would not throw AssertionError by hand, but using assertions to check invariants is a good thing. – atamanroman Mar 14 '11 at 08:30
  • 1
    `assert` needs to be turned on to function. You may want this check to occur all the time. – Peter Lawrey Mar 14 '11 at 08:32
  • In fact, I had considered `IllegalStateException`, but its documentation says "Signals that a method has been invoked at an illegal or inappropriate time." which is not the case. – fredoverflow Mar 14 '11 at 08:42
  • Have a look at IllegalBlockingModeException, IllegalComponentStateException, InvalidMarkException which all extend IllegalStateException. These indicate the object is in an illegal state to be used. IMHO This could include a `validate()` method – Peter Lawrey Mar 14 '11 at 09:00
  • But I do not want do indicate an "illegal state to be used", I want to indicate a *programming error* inside `Foo`. – fredoverflow Mar 14 '11 at 09:02
  • 1
    I would suggest an AssertionError is approriate for programming errors. – Peter Lawrey Mar 14 '11 at 09:04
1

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

thkala
  • 76,870
  • 21
  • 145
  • 185