Lesson 40 +10 XP

Java Exceptions

Java Exceptions

When something goes wrong while a program runs, Java throws an exception. You can catch exceptions to handle errors gracefully.

Checked vs unchecked

  • Checked exceptions are checked at compile time.
  • Unchecked exceptions (like runtime errors) happen while the program runs.

The try catch block

try {
  int[] myNumbers = {1, 2, 3};
  System.out.println(myNumbers[10]); // this throws an error
} catch (Exception e) {
  System.out.println("Something went wrong.");
}

If an error happens inside try, the code in catch runs instead of crashing.

The finally block

finally always runs, whether or not an exception happened:

try {
  int[] myNumbers = {1, 2, 3};
  System.out.println(myNumbers[10]);
} catch (Exception e) {
  System.out.println("Something went wrong.");
} finally {
  System.out.println("The 'try catch' is finished.");
}

The throw keyword

Use throw to create your own exception:

static void checkAge(int age) {
  if (age < 18) {
    throw new ArithmeticException("Access denied");
  } else {
    System.out.println("Access granted");
  }
}

TL;DR

  • Exceptions are errors that happen while running.
  • try...catch handles errors without crashing.
  • finally always runs.
  • throw creates a custom exception.