Handling Exceptions with try..catch
An exception is an event that disrupts the normal flow of control in a program.
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 Program Leaves Its Planned Path
Most programs are written as a sequence of steps that the computer carries out one after another. The path the program follows from start to finish is usually that sequence. Sometimes, though, something happens while the program is running that pulls it off that path. Programmers have a word for these moments: exception. This article explains what an exception does to the path a program takes, how Java represents an exception, and how try..catch fits into the picture as the place where such an event can be handled.
Before looking at Java, it helps to picture a simple program as a list of statements. Imagine a program with four statements that run in order. If nothing unusual happens, the computer runs statement one, then two, then three, then four. Now imagine that during statement two, something happens that the program did not plan for. Where does the computer go next? Keep that question in mind as you read the next section, because answering it is the whole point of the concept.
Normal Flow and the Disruption an Exception Causes
The phrase normal flow of control refers to the order in which a program's statements are executed when nothing unusual happens. An exception is an event that disrupts this normal flow. The disruption is the defining feature: the event changes which part of the program runs next, instead of letting the statements continue in their planned order.
The diagram below compares the two situations. The top path is the ordinary path, where each statement leads to the next. The middle of the disrupted path is the point where the planned order is interrupted. The exception object is the form the event takes once it exists in the program, and the try..catch handler at the end is the place the source associates with dealing with this kind of event. The diagram is a map of the idea rather than a complete description of every step the runtime takes.
Read the diagram as a comparison. On the normal path, Statement 3 and Statement 4 run because execution simply continues in order. On the disrupted path, the event in the middle changes where execution goes. The statements that were planned after the event do not continue in their planned order, and control moves toward the exception object and the handler. The key idea is not the specific steps but the change of route: an exception is defined by the fact that it changes which part of the program runs next.
Exceptions as Objects of Type Exception
In Java, exceptions are represented as objects of type Exception. This matters because an object can be created, passed around, and examined like any other value in the program. Instead of the event being an abstract interruption with no form, it becomes something the program can hold and work with.
The word Exception names the general category. The exceptions a program actually meets are usually defined by subclasses of Exception, which are narrower classes built on top of the general one. So Exception is the broad kind of thing, and specific exception types are the more precise kinds that sit beneath it.
Specific Exception Types as Subclasses
Different subclasses represent different types of exceptions, so each specific type stands for a particular category of disruption. The source highlights two examples: NumberFormatException and IllegalArgumentException. Both are named as specific kinds of Exception. The diagram below shows the relationship the source describes: the general Exception type with specific subclasses beneath it.
The source does not describe any further relationship between these two subclasses, so the diagram places them side by side rather than inventing a parent-child link between them. The source also states that it looks at only these two types in that section. Many other exception types exist beyond the two shown, so treat them as examples of a larger family rather than a complete list.
Reading an exception type name
A program meets an exception whose type is NumberFormatException. What can you conclude from the source about what kind of exception it is?
- 1Identify the general category
The type is named as a specific kind of Exception, so it belongs to the general exception family.
- 2Identify the specific kind
NumberFormatExceptionis one of the named subclasses. It stands for a particular category of disruption, distinct from other subclasses such asIllegalArgumentException. - 3Limit the conclusion to what the source says
The source does not explain when this specific exception is raised, so the safe conclusion is only that it is a named subclass of Exception representing one particular category.
NumberFormatException is a specific subclass of Exception. It is one named category of exception, and the source does not say more about its conditions.
Why the Word Exception Is Preferred to Error
It would be natural to call every disruption an error, but the source deliberately avoids that word. The reason is that some exceptions are not errors at all. You can sometimes think of an exception as simply another way to organize a program. An event that changes the path through the code is not always a mistake. It may be a situation the program was designed to route differently.
| Term | What it signals | Does it imply a mistake? |
|---|---|---|
| Exception | An event that disrupts the normal flow of control | Not necessarily; it may be an ordinary situation the program was arranged to handle |
| Error | A problem that the word itself suggests is wrong | Yes, the word implies something has gone wrong |
Why the source prefers exception when the two cases differ
Common Misreadings of the Exception Concept
Common mistake Treating every exception as an error
Why it failsThe source says some exceptions are not errors at all and can be a way to organize a program.
Do this insteadAsk whether the event is a true problem or an ordinary situation the program routes differently.
Common mistake Thinking an exception only means the program stops
Why it failsThe source defines an exception by what it does to the flow of control: it disrupts the normal order of statements.
Do this insteadFocus on which statement runs next after the event, not only on whether the program ends.
Common mistake Assuming Exception and its subclasses are the same thing
Why it failsException is the general category, and specific exception types are narrower classes built on top of it.
Do this insteadRead Exception as the broad family and NumberFormatException or IllegalArgumentException as particular members.
Common mistake Assuming the two named examples are the only exception types
Why it failsThe source names two examples and says it looks at only these two in that section, so many others exist.
Do this insteadTreat the named types as illustrations of a larger set.
Tracing a Disrupted Path
What do you think happens?
A program has four statements that normally run in order. An exception occurs during statement two. Do statements three and four still run in their planned order?
Reveal answer
No. The exception disrupts the normal flow, so execution does not simply continue in the planned order after the event.
The defining feature of an exception is that it changes which part of the program runs next. Statements three and four are on the normal path that the event has interrupted, so they are not reached in their planned order. Execution instead moves toward the exception object and the place where the event is handled.
Take the four-statement program from the prediction. Draw your own version of the diagram showing the normal path and the disrupted path. Label where the exception event occurs, what form it takes once it exists, and where the handling happens. Then write one sentence explaining why calling this event an exception rather than an error is the better choice when the event is an ordinary situation.
Hints
- Start by drawing the normal path as a straight line of four boxes.
- Branch off the normal path at the point where the event occurs.
- Remember that the source describes the exception object as the form the event takes once it exists.
Key Takeaways
- An exception is an event that disrupts the normal flow of control, changing which part of the program runs next instead of letting statements continue in their planned order.
- In Java, exceptions are represented as objects of type Exception, and specific exception types are usually subclasses of Exception.
NumberFormatExceptionandIllegalArgumentExceptionare two named examples of specific exception types discussed in the source.- The source prefers the word exception to error because some exceptions are not errors at all and can be a way to organize a program.
- The try..catch handler is the place the source associates with handling exceptions; the source pack does not describe its detailed syntax.