What exception should I use when running code that should not run?

if (stuff) doThings(); else if (something) doOtherThings(); else if (otherStuff) doStuff(); else // .. this isn't supposed to be reached 

In situations like the above, I like to put else at the end so that I can be notified if the program runs code that it should not run, which means that something went wrong (i.e. one of the above conditions must be true, but none of them means that means that something is wrong).

What exception should I use in this finale to report that something is wrong?

+5
source share
2 answers

IllegalStateException is a good candidate.

According to the Java API:

Signals that the method was called at an illegal or inappropriate time. In other words, the Java environment or Java application is not in the appropriate state for the requested operation.

In other words, your program is in a state for which there is no transition defined for this entry "This should not be achieved."

If your stuff , something and otherStuff are associated with method arguments, you can also use IllegalArgumentException , for example:

 if (arg == null) doThings(); else if (arg.endsWith("foo")) doOtherThings(); else if (arg.endsWith("bar")) doStuff(); else throw new IllegalArgumentException( "arg should be null or end with \"foo\" or \"bar\""); 
+8
source

You can create your own custom exception class by extending the Exception class.

For instance:

 class CustomException extends Exception { ... } 

And then:

 if (stuff) doThings(); else if (something) doOtherThings(); else if (otherStuff) doStuff(); else throw new CustomException(); 
+3
source

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


All Articles