The Coder's Handbook

Exceptions

WHAT ARE EXCEPTIONS?

Know Your Exceptions


You've likely encountered a lot of runtime errors called exceptions over your time writing code in Java or Processing. Some examples include:

  • NullPointerException - Using an object that hasn't been initialized

  • ArrayIndexOutOfBoundsException - Referencing an invalid index in an array

  • FileNotFoundException - Invalid filename or path


Handling Exceptions


When you encounter an exception, you can do one of two things:

  • Use a try/catch block to handle the exception

  • Throw the exception to higher-level code that called this method

The Mongols are the exception to most things in history.

TRY / CATCH

Catching Exceptions


You'll surround a section of code with a try block then immediately follow it with a catch block. Essentially, your code will try to execute the code in the try block. If something goes wrong, it jumps to the catch block instead.


In theory you can do something to try and resolve an error and change your program's behavior. But at the very least, you can print out an error message or a stack trace. This makes debugging easier and can stop your program from crashing.


Consider the example below. Assume some elements, like the array and scanner have already been declared and initialized appropriately.

An Example


try

{

int index = scan.nextInt(); // The user chooses an index

System.out.println(arr[index]); // Print out the specified index

}

catch(Exception e)

{

System.out.println("Something went wrong.");

}


You can also write a catch statement that only handles a specific type of exception. Consider an alternate version of the catch block:


catch(ArrayIndexOutOfBoundsException e)

{

System.out.println("Invalid input - index out of bounds");

}



THROW

Throwing Exceptions


Sometimes you don't know how to handle an error at its source, or you're writing dangerous code that could reasonably cause an error. You then label your code as throwing an exception. This means that the code that calls you is responsible for catching the error.


What happens if that code throws an error? It keeps going up the chain. Eventually, if an error isn't handled, it will crash your program and print a message to the console.


void fileReader(String filename) throws FileNotFoundException

{

File dataFile = new File(filename);

// more code that reads the file

}


Note that if you write a method that calls fileReader, it will be required by your compiler to either :

  • Throw the exception

  • Surround the call to fileReader() with a try / catch block.

If you just keep throwing exceptions without catching them, your program will eventually crash.

RESOURCES