Handle an exception with try and catch
20 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
Example 1 · Splitting a bill safely
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"); }}Cannot split among 0 friends Thank you for using the app
What this code does
bill / friendsthrowsArithmeticException, so theEach paysline is skipped and the catch block runs.catch (ArithmeticException e)names the type to catch;eis a variable that holds the exception. Any name works, buteis 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
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"); }}Before No such subject Program continues
What this code does
Beforeprints.marks[5]throws, soAfternever prints.- Java jumps straight to the catch block; there is no way back into
try. - After the catch block,
Program continuesruns as normal.
Trace the code
Watch both paths, one step at a time
Variables
None yet.
Output
(nothing printed yet)Line 3The array holds two inputs: a good one and a bad one.
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
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"); }}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")throwsNumberFormatException, but the only catch block is forArithmeticException.- Nothing matches, so the program stops just as if there were no try-catch:
Donenever 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 3Read 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.
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()); } }}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