Java Exceptions

try, catch, finally and throw.

✍️ 2 exercises in this lesson

Exceptions signal errors at runtime.

  • try { } catch (ExceptionType e) { } finally { }
  • throw new IllegalArgumentException("message");
  • Checked exceptions (like IOException) must be caught or declared with throws.
  • Unchecked exceptions (RuntimeException and subclasses) do not have to be.
  • Try-with-resources closes files and connections automatically: try (var r = new FileReader(f)) { }

Key Takeaways: Java Exceptions

Mastering Java Exceptions helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java Exceptions Code Example

Java
public class Main {
    static int divide(int a, int b) {
        if (b == 0) throw new ArithmeticException("Cannot divide by zero");
        return a / b;
    }

    public static void main(String[] args) {
        try {
            System.out.println(divide(10, 2));
            int[] nums = {1, 2, 3};
            System.out.println(nums[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Bad index: " + e.getMessage());
        } finally {
            System.out.println("Finished");
        }

        try {
            divide(1, 0);
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
    }
}
Output
5
Bad index: Index 5 out of bounds for length 3
Finished
Cannot divide by zero
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java Exceptions Practice Exercises

Check what you learned in “Java Exceptions”.

/ 2 solved
Fill in the blank

Handle the exception.

try {
  risky();
}  (Exception e) {
}
✓ Correct! Not quite. Try again.
Multiple choice

Checked exceptions must be…

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services