Java Exceptions
Exceptions
Robust Methods
A Robust method is one that handles bad (invalid or absurd) inputs reasonably.
Testing Exceptions
If an exception is thrown in a test, and the exception is not handled, it will fail the test. Use a try-catch statement to pass the test.
try {
obj.someMethodThatThrowsException(badInput);
fail("The expected exception was not thrown")
} catch (ExpectedException ex) {
return;
}
Throwing Exceptions
The method definition should be
@Override
public T get(int index) throws IndexOutOfBoundsException {
...
}
throw new Exception("Index out of bound")
is bad practice.
If the method throws many exceptions, use commas to separate them (better). Or, if there is one common parent exception, you can use throws the parent exception.
Exception Hierarchies
Exceptions are classes, so there can be an hierarchy. The Throwable class is the super-class of all errors and exceptions in the Java language. Only objects that are instances of this class are thrown by the JVM or throw statement.
- If an exception is declared to be caught, any of its sub-classes will also be caught.
- You must deal with specific exceptions first.
In Java, there are two types of exceptions:
- Check exception
- The compiler will force you to deal with this type of exception in the source code, like by wrapping with a try-catch block or adding the exception to the method header.
- Or, allow the
doSomethingmethod to throw the exception raised bydoThisFirst. Node:doSomethingcallsdoThisFirst. - All Java exceptions are checked unless they subtype the
ErrororRuntimeExceptionclass.
- OnCheck exception
- The compiler does not bother with this.
All the exceptions we will work with in this class will be a runtime exception.
- we put the exception in the method line because it is good practice and is good coding practice.
Custom Exceptions
Creating custom exceptions can be as simple as extending an existing built-in exception.
public class IndexException extends RuntmeException {
public IndexException() {
}
public IndexException(String message) {
super(message);
}
}Linked from Data Structures