AI Hints
Home›Java Tutorial›What Exceptions Are, try and catch, and finally
Java · Lesson 92 of 120

try and catch

Handle the problem.

⏱ 2 min read▶ Video at 1:56:44🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

You can catch an exception, and deal with it, instead of letting the program crash. Put the risky code in a try block, and the rescue code in a catch block.

  • Risky code in try
  • Rescue in catch
  • No crash

Skipping bad input

Parse int throws a number format exception, when the text isn't a number. We put it inside try. If it throws, Java jumps straight to the catch block. Get message describes the problem. Then the loop carries on, as normal. Run it. Forty two and eight are added. Seven, written as a word, is skipped. And the total is fifty.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String[] inputs = {"42", "seven", "8"};
        int total = 0;
        for (String s : inputs) {
            try {
                int n = Integer.parseInt(s);
                total += n;
                System.out.println("Added " + n);
            } catch (NumberFormatException e) {
                System.out.println("Skipped '" + s + "': " + e.getMessage());
            }
        }
        System.out.println("Total: " + total);
    }
}
Output
Added 42
Skipped 'seven': For input string: "seven"
Added 8
Total: 50

Several catches

One try can have several catch blocks, for different exceptions. Java uses the first one that matches. A vertical bar catches two types in one block. Run it. Four. Not a number. Arithmetic exception, from dividing by zero. And an index out of bounds.

Main.javajava
public class Main {
    static void test(String text, int index) {
        try {
            int n = Integer.parseInt(text);
            int[] data = {10, 20, 30};
            System.out.println(data[index] / n);
        } catch (NumberFormatException e) {
            System.out.println("Not a number: " + text);
        } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
            System.out.println("Problem: " + e.getClass().getSimpleName());
        }
    }
    public static void main(String[] args) {
        test("5", 1);
        test("five", 1);
        test("0", 1);
        test("2", 9);
    }
}
Output
4
Not a number: five
Problem: ArithmeticException
Problem: ArrayIndexOutOfBoundsException

try and catch

Only catch exceptions you can actually handle. Catch the most specific type you can. Never leave a catch block empty, or problems disappear silently. And let the rest bubble up.

keyvalue
try { }risky code
catch (Type e)what to do
Specificcatch exact types
Neveran empty catch

Summary

Put risky code in try, and handle problems in catch. Several catch blocks can handle different types. Next, finally.

Key takeaways
  • try { … }
  • catch (Type e) { … }
  • Specific types
Next up: finally — always runs