Throwing and Declaring Exceptions
A try..catch statement lets a program catch a thrown exception of a named type and keep running instead of crashing.
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
- Statements in try run until one raises an exception; the rest of try is skipped.
- Python checks the except clauses in order and runs the first one whose type matches.
- If nothing was raised, the else block runs instead.
- 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.
Loading the simulation…
When a Problem Stops the Program
Programs often run into problems they cannot handle on their own. A program that runs into such a problem does not simply continue past it. Consider the method Integer.parseInt(str). If the text in str is not a legal number, the method 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.
Left alone, a thrown exception ends the program. Java gives you 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 focuses on how that statement is written and, more importantly, how the computer moves through it step by step. Watching that movement is the key to understanding it, so pay close attention to the moment the normal flow of statements is interrupted and to what runs next.
Predicting the Path Through a Try Part
What do you think happens?
Suppose every statement inside the try part finishes without any problem. What happens to the catch part?
Reveal answer
The catch part is skipped and the program carries on with the rest of the program.
The try part runs first. If it finishes without any exception, the computer skips the catch part entirely and continues with the rest of the program.
Commit to an answer in your head before reading on. Your prediction is the right starting point for tracing the code. The question to keep in mind is simple: at what point does the normal order of the try part stop, and where does execution go next?
The General Form of try..catch
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.
The placeholders in angle brackets are filled in by you, and in the general form above they appear as Statements-1, ExceptionClassName, variableName, and Statements-2. 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. 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. If the try part finishes without any exception, the computer skips the catch part entirely and carries on with the rest of the program. 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.
int number;
try {
number = Integer.parseInt(text);
System.out.println("Converted: " + number);
} catch (NumberFormatException e) {
System.out.println("Problem: " + e.getMessage());
}
System.out.println("Program continues");- 1If text holds a legal number such as 42,
parseIntsucceeds, the Converted line runs, the catch part is skipped, and the final line runs. - 2If text holds something like abc,
parseIntthrows aNumberFormatException. The rest of the try part, including the Converted line, is passed over. Control jumps directly to the catch part, which prints a problem message using the exception object. - 3After the catch part finishes, the program continues with the statement after the try..catch, so the final line still runs and the program does not crash.
- The try part holds the statement that might fail
- The catch clause names
NumberFormatExceptionand uses the variable e
The key observation is the moment the normal order is interrupted. Statements in the try part that come after the failing statement never run, and the catch part takes over. The program is not stopped by the exception, because the catch clause handled it.
The Catch Variable and Printing the Exception
An exception is represented by an object. The variable name in the catch clause is a 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.
The variable is only meaningful inside the catch part, because that is where the exception object is available. The name you pick is your choice, so long as it follows the normal naming rules of the language. In the example above the name e was used, but any valid name would work in the same position.
Imagine a program that reads a quantity typed by a user. When the text is not a number, the catch part can print the exception's message to show what went wrong, and then the program can ask for input again instead of stopping. The variable is what makes that specific message available to the catch part.
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, and it will crash the program just as it would have without any try..catch at all.
- The catch clause names only
NumberFormatException - A different exception raised inside the try part is not matched by this catch
Mistakes Beginners Make with try..catch
Common mistake Leaving out the braces around the try part or the catch part
Why it failsBraces are required around both parts of the statement.
Do this insteadAlways wrap Statements-1 and Statements-2 in their own pair of braces.
Common mistake Assuming any exception will be caught by the catch clause
What it looks likeA catch clause names NumberFormatException but an unrelated exception occurs in the try part.
Why it failsA try..catch handles only the exception type it names, so other exceptions still crash the program.
Do this insteadName the exception type that can actually occur, and recognize that other types are not handled by that catch.
Common mistake Expecting the rest of the try part to run after an exception occurs
Why it failsWhen an exception of the named type occurs, the computer does not finish the rest of the try part. It jumps directly to the catch part.
Do this insteadTrace the try part and stop at the failing statement; the statements after it are skipped.
Common mistake Using the catch variable outside the catch part
Why it failsThe variable is only meaningful inside the catch part, where the exception object is available.
Do this insteadUse the variable only within the braces of the catch clause.
Practice Tracing a try..catch
Consider a try part whose first statement can throw NumberFormatException and whose second statement prints Done. The catch clause names NumberFormatException and prints a message. Trace what runs when the first statement succeeds, and then trace what runs when it throws. In each case, list which statements run and state whether the program continues after the try..catch.
Hints
- When nothing is thrown, the catch part is skipped and every try statement runs in order.
- When the named exception is thrown, statements after the failing one in the try part are passed over and control jumps to the catch part.
- After the catch part finishes, the program continues with the statement after the try..catch.
A try part contains a statement that throws ArithmeticException, but the catch clause names NumberFormatException. Explain whether the catch part runs and what happens to the program.
Hints
- Ask whether the thrown exception is the type named in the catch clause.
- Think about what the source says happens to exceptions of any type other than the one named.
Scope of This Article
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 with no exception, the catch part is skipped. If a matching exception occurs, control jumps directly to the catch part and then continues after the statement.
- The catch variable refers to the exception object, which carries an error message that is displayed when the object is printed.
- A try..catch handles only the exception type it names; any other exception still crashes the program.