if (stuff) doThings();
else if (something) doOtherThings();
else if (otherStuff) doStuff();
else // .. this isn't supposed to be reached
In situations such as the one above, I like to put the else
in the end so I can be notified if the program runs code it shouldn't run, meaning something went wrong (i.e. one of the above conditions should be true, but none are, which means something is wrong).
What exception should I throw in that final else, to notify me something is wrong?
Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.
An exception should be thrown when a function experiences a failure, i.e., an error. A function is a unit of work, and failures should be viewed as errors or otherwise based on their impact on functions.
Also when you catch all exceptions, you may get an exception that cannot deal with and prevent code that is upper in the stack to handle it properly. The general principal is to catch the most specific type you can. catch(Exception) is a bad practice because it catches all RuntimeException (unchecked exception) too.
The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.
The IllegalStateException
is a good candidate.
As the Java API states:
Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.
In other words, your program is in a state for which there is no transition defined for that "this isn't supposed to be reached" input.
If your stuff
, something
and otherStuff
are all related to your method arguments, you could also use IllegalArgumentException
, like:
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\"");
You can create your own custom exception class by extending the Exception class.
For example:
class CustomException extends Exception {
...
}
And then:
if (stuff)
doThings();
else if (something)
doOtherThings();
else if (otherStuff)
doStuff();
else
throw new CustomException();
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