Error handling and Exceptions

Debugging can be done using: - debugger - logging (check log4j framework)

Stack: sorted pile of not completed processing routines


Exceptions are objects. These objects are instances of subclasses of one of following three error classes: - Error: system errors (nothing to do about) - Runtime Exceptions: Programming errors (unchecked) - Exceptions all other (checked).

Run-time errors

Run-time errors are elicited by

  • wrong input
  • programming errors
  • stack overflow
  • error memory assignment

Examples of RunTime Exceptions: - NullPointerException - ArithmeticException - ArrayIndexOutOfBoundsException

Unchecked exceptions can but do not need to be handled.

Checked Exception handling

Checked exceptions need to be handled, otherwise the compiler will complain. In general, there are two ways to do so.

  1. You can create a try/catch block and catch the exceptions right away.
  2. You propagate the exception by adding a ‘throws MyException’ to the signature of the method. This means that the exceptions needs to be handled on the upper level.

Exceptions implement the interface Throwable. They can be instantiated like any other object

Order of exceptions handling

Specific exceptions catch blocks need to be placed above more general ones as general exceptions will always also catch the specific ones. By doing so, the specific catch block is unreachable and the compiler will complain.

Also worthnoty is that the finally block will always be executed, independently of the statements in the try or catch block. also, if try contains return statement.

Try-with resources

Since Java 1.7 it is possible to integrate the catch block into the try block. This is for example important for streams that need to be closed also if unexpected behavior occurs. The syntax of such a try block is as follows:

try(PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(myFile, false)))){
pw.println("Hello world!");