Skip to lesson

Handle an exception with try and catch

A try block holds code that might throw an exception. A catch block runs only when that exception happens, so the program can carry on instead of crashing.

try and catch

The bill app crashes and its thank-you line never prints. Put the risky lines in a try block and say what to do instead in a catch block: this is called catching, or handling, the exception.

Syntax
try {
risky lines
} catch (ExceptionType e) {
what to do instead
}

Example 1 · Splitting a bill safely

SafeSplit.javaJava
public class SafeSplit {    public static void main(String[] args) {        int bill = 900;        int friends = 0;        try {            int share = bill / friends;            System.out.println("Each pays: " + share);        } catch (ArithmeticException e) {            System.out.println("Cannot split among 0 friends");        }        System.out.println("Thank you for using the app");    }}
Output
Cannot split among 0 friends
Thank you for using the app

What this code does

  • bill / friends throws ArithmeticException, so the Each pays line is skipped and the catch block runs.
  • catch (ArithmeticException e) names the type to catch; e is a variable that holds the exception. Any name works, but e is the usual one.
  • The program does not stop: the thank-you line after the catch block still prints.

What runs and what is skipped

Which lines run when the problem happens halfway through try? The rest of try is skipped, Java jumps to catch, and then carries on after it. With no exception, the catch block is skipped instead.

Example 2 · Lines after the problem are skipped

SkipDemo.javaJava
public class SkipDemo {    public static void main(String[] args) {        int[] marks = {78, 85, 62};        try {            System.out.println("Before");            System.out.println(marks[5]);            System.out.println("After");        } catch (ArrayIndexOutOfBoundsException e) {            System.out.println("No such subject");        }        System.out.println("Program continues");    }}
Output
Before
No such subject
Program continues

What this code does

  • Before prints. marks[5] throws, so After never prints.
  • Java jumps straight to the catch block; there is no way back into try.
  • After the catch block, Program continues runs as normal.

Trace the code

Watch both paths, one step at a time

public class AgeInputs {
public static void main(String[] args) {
String[] inputs = {"18", "abc"};
for (String text : inputs) {
try {
int age = Integer.parseInt(text);
System.out.println("Age next year: " + (age + 1));
} catch (NumberFormatException e) {
System.out.println("Not a number: " + text);
}
}
System.out.println("Done");
}
}

Variables

None yet.

Output

(nothing printed yet)

Line 3The array holds two inputs: a good one and a bad one.

Step 1 of 9
Keep only the risky line and the lines that need its result inside try.

Catch the right type

A catch block handles only its own exception type. If the try block throws NumberFormatException but you catch ArithmeticException, nothing catches it and the program still stops.

Example 3 · The wrong catch does not help

WrongCatch.javaJava
public class WrongCatch {    public static void main(String[] args) {        try {            int age = Integer.parseInt("abc");            System.out.println("Age: " + age);        } catch (ArithmeticException e) {            System.out.println("Please type digits");        }        System.out.println("Done");    }}
Sample output
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:665)
	at java.base/java.lang.Integer.parseInt(Integer.java:781)
	at WrongCatch.main(WrongCatch.java:4)

What this code does

  • parseInt("abc") throws NumberFormatException, but the only catch block is for ArithmeticException.
  • Nothing matches, so the program stops just as if there were no try-catch: Done never prints.

The fix is to catch the type that is really thrown, catch (NumberFormatException e). The first line of the stack trace tells you which type that is.

Find the bug

Spot the bug

Select the line that is wrong.

This should print Please type digits, but it crashes.

Round 1 of 3

Read the details: getMessage()

A catch block often needs to say what exactly went wrong. e.getMessage() returns the exception's message: the same text that follows the colon in a stack trace.

RightCatch.javaJava
public class RightCatch {    public static void main(String[] args) {        try {            int age = Integer.parseInt("abc");            System.out.println(age);        } catch (NumberFormatException e) {            System.out.println("Not a number: " + e.getMessage());        }    }}
Output
Not a number: For input string: "abc"

The message helps you while testing. For real users, a plain sentence such as Please type digits only is often kinder.

Next step

Check your understanding

8 quick questions