Handling Exceptions in Java - ilya-khadykin/notes-outdated GitHub Wiki
Types of exceptions
| Exception type |
Comment |
java.lang.Error |
exception in JVM itself (should not be handled by programmer) |
java.lang.Exception |
checked exceptions in user`s code |
java.lang.RuntimeException |
unchecked exception in user`s code |
- checked exceptions should be always handled by programmer, Java enforces that.
- unchecked exceptions (sub classes from
java.lang.RuntimeException (java.lang.NullPointerException, java.lang.ArrayIndexOutOfBoundsException, java.lang.ArithmeticException) are not suppose to be handled and programmer not force to handle them in his\her code.
Custom Exception
public class CalculatorException extends RuntimeException {
public CalculatorException(String message) {
super(message);
}
public CalcualtorException(String message, Throwable cause) {
super(message, cause);
}
}
public class CalculatorImpl implements Calculator {
@Override
public double calculate(String expr) {
// Since it's derived from RuntimeException is can't be left unchecked
throw new CalculatorException("Unsupported operator found");
//...
}
}
Handling Exceptions
try {
//
} catch (TypeOfException ex) {
// log the error
System.err.println("An Error occurred");
}
References
- Java Programming Basics by Simon Roberts