Try-Catch Block in Java

Naveen AnamaneniUpdated · 4 min read
easyJava 25javaexceptions

A try-catch block is a safety net around code that might fail. You put the risky statements in try, and in catch you say which kind of problem you're ready for and what to do about it. If the problem happens, Java jumps straight to your catch; if it doesn't, the catch is skipped as if it weren't there. Watching that jump happen line by line is the best way to understand it.

Step by Step

No problem: catch is skipped. A problem: jump straight to catch
SplitBill.java▶ Try it
public class SplitBill {
    static void split(int bill, String people) {
        try {
            int n = Integer.parseInt(people);
            System.out.println("Each pays Rs. " + bill / n);
        } catch (NumberFormatException e) {
            System.out.println("'" + people + "' isn't a number of people");
        }
        System.out.println("Done with " + people);
    }
 
    public static void main(String[] args) {
        split(1200, "4");
        split(1200, "four");
    }
}
Output
Each pays Rs. 300
Done with 4
'four' isn't a number of people
Done with four

How it works

  1. With "4", both lines in try run, the catch is skipped, and the method continues after it.
  2. With "four", parseInt throws a NumberFormatException. The println after it in try is skipped. Java looks for a catch that matches the exception's type, finds one, and runs it.
  3. After the catch, execution continues normally with "Done with four".

What the Exception Object Tells You

The variable in catch (NumberFormatException e) is the exception object itself. Its methods describe the problem:

Inspect.java▶ Try it
public class Inspect {
    public static void main(String[] args) {
        try {
            Integer.parseInt("12a");
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
            System.out.println(e);
            System.out.println(e.getClass().getName());
        }
    }
}
Output
For input string: "12a"
java.lang.NumberFormatException: For input string: "12a"
java.lang.NumberFormatException
MethodReturns
getMessage()The detail message
toString() (or printing e)The class name and the message
getClass().getName()The exception's class
printStackTrace()Prints the full stack trace to the error stream
getCause()The exception that caused this one, if any

Variables and Scope

A variable declared inside try exists only inside try. If you need the value afterwards, declare the variable before the try and give it a default:

Scope.java▶ Try it
public class Scope {
    public static void main(String[] args) {
        int qty = 1;
        try {
            qty = Integer.parseInt("x3");
        } catch (NumberFormatException e) {
            System.out.println("Using the default quantity");
        }
        System.out.println("Quantity: " + qty);
    }
}
Output
Using the default quantity
Quantity: 1

Common Mistakes

An empty catch block. The problem disappears silently; at least print or log it.

Declaring the variable inside try and using it after. It's out of scope; declare it before.

Catching a type that the code can't throw. For checked exceptions, it's a compile error ("is never thrown in body of corresponding try statement").

Practice

  1. Easy: Read an age as text, parse it in a try, and print "Invalid age" for bad input. Use a default of 0.
  2. Harder: Write static int[] parseAll(String[] items) that returns the numbers it could parse and prints a message for each item it skipped.

Quick check: try-catch

4 questions
1When does a catch block run?
2What happens to the statements after the failing line in try?
3What does e.getMessage() return for Integer.parseInt("12a")?
4Where should a variable used after the try-catch be declared?

Key Takeaways

Was this tutorial helpful?

Lesson 219 of 482