Concepts / Multiple catch Clauses and Exception Types

Multiple catch Clauses and Exception Types

A try..catch statement lets a program catch a thrown exception of a named type and keep running instead of crashing.

  • Programming
Interactive lab

Try it: try / except / else / finally

How an exception jumps out of a try block to the first matching except clause, when else runs, and why finally always runs.

How it works

  1. Statements in try run until one raises an exception; the rest of try is skipped.
  2. Python checks the except clauses in order and runs the first one whose type matches.
  3. If nothing was raised, the else block runs instead.
  4. finally runs in every case.

Default run (9 steps): Call safe_divide('4'). … Return 25.0. Output was: Worked: 25.0 / Done.

Simplified: One fixed function; int() and / are modelled exactly (including how Python prints floats), but nothing is executed as Python.

Educational simulation

Loading the simulation…

When a Problem Interrupts a Program

Programs often run into problems they cannot solve on their own. Consider a method such as Integer.parseInt(str). If the text stored in str is not a legal number, the method cannot produce an int. It reports the problem by throwing an exception of type NumberFormatException. In everyday programming language, we say the exception was thrown at the point where the problem occurred.

A program that runs into a problem it cannot handle does not simply continue past it. Left alone, a thrown exception ends the program. Java provides a way to catch the exception at the point where it happens and carry on. The tool for this job is the try..catch statement. This article looks at how that statement is written and, more importantly, how the computer moves through it step by step.

What do you think happens?

Suppose every statement inside the try part finishes without any problem. What happens to the catch part?

  • The catch part runs once, after the try part finishes

  • The catch part is skipped entirely

  • The catch part runs before the try part starts

Reveal answer
Answer:

The catch part is skipped entirely

If the try part finishes without any exception, the computer skips the catch part and carries on with the rest of the program. The catch part only matters when a matching exception occurs.

The Shape of a try..catch Statement

The simplified form of a try..catch statement has two pieces that work together. The first piece is a try part, which holds a group of statements inside braces. The second piece is a catch part, which names an exception class and a variable, and then holds its own group of statements inside braces. Braces are required around both parts.

java

The placeholders in the general form are filled in by you. Statements-1 are the ordinary statements you want to protect. The exception class name is the specific type of exception the catch part is willing to handle, such as NumberFormatException or IllegalArgumentException. The variable name is a name you choose to refer to the exception object, so long as it follows the normal naming rules of the language. Statements-2 are the statements that run only when the matching exception occurs.

Tracing the Two Paths Through the Statement

When the computer reaches a try..catch statement, it begins by executing the statements in the try part. From there, the story splits into two main paths. The diagram below traces both. Follow the arrows from the top, and notice where the normal order of the try part is interrupted.

If the try part finishes without any exception, the computer skips the catch part entirely and carries on with the rest of the program. Every statement in the try part runs in its normal order, and none of them are passed over. If an exception of the named type occurs during the try part, the computer does not finish the rest of the try part. It immediately jumps from the place where the exception occurred to the catch part, runs the catch statements, and then continues with the program after the statement. Any try part statements that come after the point of failure are the ones that get passed over.

java
Output
Parsed: 42
Program continues.
Notes on the code
  • The text 42 is a legal number, so parseInt succeeds and no exception is thrown.
  • The println inside the try part runs normally.
  • The catch block is skipped, and the final line runs as the next statement.
java
Output
Could not parse: For input string: "abc"
Program continues.
Notes on the code
  • The text abc is not a legal number, so parseInt throws NumberFormatException at that line.
  • The line that prints Parsed is passed over, because the trace jumped out of the try part.
  • The catch block runs with e referring to the exception object, and the program then continues after the statement.

What the Catch Variable Holds

An exception is represented by an object. The variable name in the catch clause is the way to get hold of that object while the catch statements run. Through that variable, you can work with the details of the problem that occurred. The exception object contains information about the cause of the exception, and this includes an error message. If you print the exception object, that error message is what gets displayed.

Definition

The exception variable is the name declared in a catch clause. It refers to the exception object that was thrown, and it is only meaningful inside the catch part, because that is the only place where the exception object is available.

Printing the variable is useful because the message tells you what went wrong. In the example above, the message reads For input string: "abc", which points directly at the value that could not be converted. A catch block can print that message, record it, or use it to decide what to do next. Outside the catch part the variable does not exist, so you cannot use it there.

When the Catch Clause Does Not Match

A try..catch statement handles only the exception type it names. Suppose the catch clause names NumberFormatException, but a different kind of exception occurs during the try part. That other exception is not caught by this statement. It will crash the program just as it would have without any try..catch at all. The flowchart below shows the decision that causes this.

java
Output
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
Notes on the code
  • The thrown exception is NumberFormatException, but the catch names ArithmeticException.
  • The types do not match, so the catch block does not run and no message is printed by it.
  • The program ends with an error report, and the final println never executes.

Mistakes Beginners Make with Catch Clauses

  • Common mistake

    Assuming the catch block always runs

    What it looks like
    try { int n = Integer.parseInt("42"); } catch (NumberFormatException e) { System.out.println("Bad"); }
    Why it fails

    If the try part finishes without any exception, the catch part is skipped entirely.

    Do this instead

    Read the catch block as code that runs only when the named exception occurs.

  • Common mistake

    Expecting the statements after the failure point to run inside the try part

    What it looks like
    try { int n = Integer.parseInt("abc"); System.out.println("Parsed"); } catch (NumberFormatException e) { }
    Why it fails

    When the exception occurs, the computer jumps from the place where it happened to the catch part, so the println is passed over.

    Do this instead

    Put only the statements that are safe to skip inside the try part, or accept that anything after the failure point will not run.

  • Common mistake

    Using the variable name outside the catch part

    Why it fails

    The variable is only meaningful inside the catch part, because that is where the exception object is available.

    Do this instead

    Use the variable only within the braces of the catch block.

  • Common mistake

    Naming a catch type that does not match the exception that actually occurs

    What it looks like
    catch (ArithmeticException e) around Integer.parseInt("abc")
    Why it fails

    The statement handles only the type it names, so a NumberFormatException passes through and crashes the program.

    Do this instead

    Name the exception class that the try part can actually throw.

  • Common mistake

    Forgetting the braces around the try part or the catch part

Practice: Tracing a Catch Clause

EASY

Trace this code. Before you run it in your head, decide which lines print. Then state whether the program crashes. The text "7x" is not a legal integer, so Integer.parseInt("7x") throws NumberFormatException.

try {
    int n = Integer.parseInt("7x");
    System.out.println("Value: " + n);
} catch (NumberFormatException e) {
    System.out.println("Problem: " + e.getMessage());
}
System.out.println("Done");
Hints
  • Identify the exact line where the exception is thrown, and note that the println inside the try part is after that line.
  • Ask whether the thrown type matches the type named in the catch clause.
  • Once the catch block finishes, check which statement runs next.
MEDIUM

Now change the catch clause to name ArithmeticException and keep the same try part. Predict whether the program crashes, and explain your answer using the matching rule for catch clauses.

Hints
  • The Integer.parseInt call still throws NumberFormatException.
  • A try..catch statement handles only the exception type it names.

Key Takeaways

  • A try..catch statement has four parts: the try block, the exception class name, the variable name, and the catch block.
  • If the try part finishes without an exception, the catch part is skipped; if a matching exception occurs, control jumps from the failure point straight to the catch part.
  • The catch variable refers to the exception object, and printing it displays an error message describing the problem.
  • A catch clause handles only the exception type it names; any other exception still crashes the program.