CodeBlanks Logo Icon CodeBlanks

Exception hierarchy

Learn RuntimeException, IOException and others.

The exception hierarchy

All exceptions descend from Throwable. Error represents unrecoverable system failures; Exception can be handled by the programmer. The RuntimeException subclass is considered unchecked.

Throwable
  ├─ Error
  └─ Exception
       ├─ RuntimeException (unchecked)
       └─ IOException (checked)

Checked exceptions must be caught or declared with throws at compile time. IOException is an example. Unchecked ones are under RuntimeException; catching them is optional.

Common exception types

Some common exceptions: NullPointerException (using a null object), ArithmeticException (division by zero), ArrayIndexOutOfBoundsException (out of bounds index) and NumberFormatException (invalid number string).

Integer.parseInt("abc");
// NumberFormatException
int[] arr = new int[3];
int x = arr[5];
// ArrayIndexOutOfBoundsException

These all fall under RuntimeException; they are unchecked. Most can be prevented by careful coding; null checks, boundary checks and input validation are examples.

Practice Catch an invalid number

Define String s = "abc";. Inside try call Integer.parseInt(s). Catch NumberFormatException and print Sayı değil.

Starter code

Main.java
public class Main {
  public static void main(String[] args) {
    String s = "abc";
    // attempt parseInt, catch NumberFormatException, print a message
  }
}

Sample solution

Main.java
try {
  int n = Integer.parseInt(s);
  System.out.println(n);
} catch (NumberFormatException e) {
  System.out.println("Sayı değil");
}

Expected output

Sayı değil

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which of the following is an unchecked exception?

  • IOException
  • Error
  • RuntimeException Correct answer
  • Throwable

Explanation: RuntimeException and its subclasses are unchecked; catching them is optional.

2 Match each exception to its category

Term Meaning
IOException Checked
RuntimeException Unchecked
Error System error
NullPointerException null object error

3 Catch NumberFormatException

Question
try {
  Integer.parseInt(s);
} catch (____ e) {
  System.out.println("Sayı değil");
}
Answer
try {
  Integer.parseInt(s);
} catch (NumberFormatException e) {
  System.out.println("Sayı değil");
}

Explanation: NumberFormatException represents an invalid number string.

All lessons in Beginner