Skip to content
thesarfo

Concept

Exception Handling

Checked vs unchecked exceptions, try/catch/finally, try-with-resources, the exception hierarchy, throwing exceptions, and custom exceptions.

views 0

There are 3 categories of exceptions in Java: checked, unchecked, and errors.

  1. Checked exceptions — must be handled with try/catch, e.g. ClassNotFoundException, IOException, InterruptedException.
  2. Unchecked exceptions — optional to handle, e.g. ArithmeticException, IndexOutOfBoundsException, NullPointerException.

Exception hierarchy

Object
|
Throwable
|
Exception ------- Error
|
ClassNotFoundException, InterruptedException, IOException, NumberFormatException, RuntimeException
|
ArithmeticException, IndexOutOfBoundsException, NullPointerException

Exception class methods

  1. String getMessage()
  2. String toString() — called automatically by System.out.println
  3. void printStackTrace()

Try/catch

To catch an error, wrap your code in a try/catch block.

import java.io.FileNotFoundException;
import java.io.FileReader;
public class Practice {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("file.txt");
System.out.println("File open");
} catch (FileNotFoundException ex) {
System.out.println("The file does not exist");
}
}
}

Here we try to read from a file that doesn’t exist, and catch the exception in a catch block to print a user-friendly message. ex is just the conventional name for the caught exception — an instance of FileNotFoundException — and it can print a message via ex.getMessage().

The finally block

import java.io.FileReader;
import java.io.IOException;
public class Practice {
static FileReader reader = null;
public static void main(String[] args) {
try {
reader = new FileReader("file.txt");
var value = reader.read(); // read a single value from the file
} catch (IOException e) {
System.out.println("Could not read data.");
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Try-with-resources statement

This is when you initialize a try block with a resource in parentheses. That way you don’t need to specify what to do with the resource in the finally block, and you don’t need to initialize the resource before the try block.

import java.io.FileReader;
import java.io.IOException;
public class Practice {
public static void main(String[] args) {
try (FileReader reader = new FileReader("file.txt")) {
var value = reader.read(); // read a single value from the file
} catch (IOException e) {
System.out.println("Could not read data.");
}
}
}

Throwing exceptions

public class Account {
public void deposit(float value) {
if (value <= 0) {
throw new IllegalArgumentException();
}
}
}
public class Demo {
public static void show() {
var account = new Account();
account.deposit(-1); // will throw an exception to the user
}
}

What if we want to throw a checked exception — we can do that too:

import java.io.IOException;
public class Account {
public void deposit(float value) throws IOException {
if (value <= 0) {
throw new IOException();
}
}
}
public class Demo {
public static void show() {
var account = new Account();
try {
account.deposit(-1);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Custom exceptions

All custom exceptions must inherit from the Exception class.

class MinBalanceException extends Exception {
public String toString() {
return "Minimum balance should be 1.5k, try again with a smaller amount";
}
}

For a method to throw an object of the Exception class, use the throws keyword:

static void method1() throws Exception {
throw new Exception();
// you can wrap the throw statement above in a try/catch
}