Does it make sense to throw a private exception?

fredoverflow :

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?

Peter Lawrey :

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related