Does it make sense to throw a private exception?

I want to throw an exception at runtime if my class invariants are invalid. Since this is a programming error (similar to a NullPointerException), clients should not catch this exception.

Should an exception class be declared private or public (or something else)?

class Foo { // ... private static class InvariantsViolated { // ... } } 

Are there any recommendations for custom exceptions and execution visibility?

+4
source share
2 answers

You can use an existing exception if you do not expect this exception to be caught differently. If he is not caught, I do not see the need for a special exception. Some exceptions you could reuse

  • AssertionError - for me, this means that there is a fatal programming error of an unspecified type.
  • IllegalArgumentException - for me this means that only the arguments to the method were invalid.
  • IllegalStateException - for me, this means that the state of the object (for example, a combination of values) is not valid for this operation.

If you want to configure an exception, you can consider extending these exceptions or using one of the exceptions that extend them.

+3
source

I believe that for throw something, this object must implement the Throwable interface, which means that it must be either Error or Exception . Since you do not want your clients to catch this event, you should probably use Error . From the Error documentation :

A bug is a subclass of Throwable which indicates serious problems that a reasonable application should not try to catch.

This way you can avoid the terrible Exception tricks that some programmers typically use β€” most often these programmers don’t even think about catching Error at all ...

0
source

Source: https://habr.com/ru/post/1343601/


All Articles