Computer Science · Ch 1 — Exception Handling in Python
Catching Exceptions
Catching Exceptions
What Does It Mean to "Catch" an Exception?
An exception is said to be caught when a piece of code specifically designed to handle that exception actually runs. The whole point of catching is to prevent the program from crashing and to give a controlled response instead.
The try and except Blocks: The Core Mechanism
The book introduces two blocks that work as a pair:
tryblock: You place any "suspicious" lines of code here — lines where you suspect an error might occur. While writing or debugging, if you doubt an exception in a particular part of the code, that part goes insidetry.exceptblock: Everytryblock must be followed by at least oneexceptblock. Inside theexceptclause, you write the code that should run if a specific exception occurs.
How execution flows:
- Python starts executing the code inside the
tryblock normally. - If no exception occurs, the
exceptblock is skipped entirely, and execution continues with the statement after the entiretry..exceptstructure. - If an exception does occur inside the
tryblock, the remaining code insidetryis immediately stopped. Control jumps straight to the matchingexceptblock. - After the
exceptblock finishes, execution continues with the next statement after thetry..exceptblock.
Syntax of try..except
try:
[program statements where exceptions might occur]
except [exception-name]:
[code for exception handling if the exception-name error is encountered]
Example from the Book: Handling ZeroDivisionError
Program 1-2: Using try..except block
print("Practicing for try block")
try:
numerator = 50
denom = int(input("Enter the denominator"))
quotient = (numerator / denom)
print(quotient)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO.... not allowed")
print("OUTSIDE try..except block")
What happens in two cases:
- User enters a non-zero denominator: The division works,
quotientis printed, "Division performed successfully" is printed, theexceptblock is skipped, and finally "OUTSIDE try..except block" is printed. - User enters 0: The division raises
ZeroDivisionError. Execution insidetrystops immediately (theprint(quotient)and the success message are never reached). Control goes to theexceptblock, which prints "Denominator as ZERO.... not allowed". After that, "OUTSIDE try..except block" is printed.
In both cases — whether an exception occurs or not — the statement after the try..except block always executes. The except block only runs when its specific exception is raised.
Handling Multiple Exceptions with Multiple except Blocks
A single piece of code might have more than one type of error. For such situations, you can have multiple except blocks for one try block.
Program 1-3: Use of multiple except clauses
print("Handling multiple exceptions")
try:
numerator = 50
denom = int(input("Enter the denominator: "))
print(numerator / denom)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
except ValueError:
print("Only INTEGERS should be entered")
Here, two exceptions are handled:
| Exception | When it occurs | What the except block does |
|---|---|---|
ZeroDivisionError | User enters 0 as denominator | Prints "Denominator as ZERO is not allowed" |
ValueError | User enters something that is not an integer (e.g., a letter) | Prints "Only INTEGERS should be entered" |
How Python decides which except block to run: When an exception is raised, Python searches through the except blocks in the order they appear. It looks for a matching exception name. If a match is found, that block runs. If no match is found, the program terminates with an unhandled exception error.
The Catch-All except Clause (Without Specifying an Exception)
What if an exception occurs that you didn't anticipate? The book provides a safety net: you can add an except clause without specifying any exception name. This acts as a default handler for any exception not caught by earlier except blocks.
Important rule: This bare except clause must be added as the last clause of the try..except block. If you put it first, it will catch everything and the specific handlers below it will never run.
Program 1-4: Use of except without specifying an exception
print("Handling exceptions without naming them")
try:
numerator = 50 …
Drawn by us to help you understand the concept clearly, and verified to make sure it's accurate. For exams, practice from your NCERT textbook's own diagram.
This is the output of running Program 1-2, a script that wraps a division inside a try...except block to guard against dividing by zero, when the user supplies a valid, non-zero denominator. The RESTART: line shows the script's path being re-run. The program first prints Practicing for try block, then prompts Enter the denominator, to which the user types 12 (shown appended directly after the prompt text, simulating live keyboard input in the Shell).
Because 12 is a valid non-zero number, the division inside the try block completes without any problem, so Python prints Division performed successfully — the message the try block itself was written to show on success — and the except block is skipped entirely since no exception occurred. Finally, OUTSIDE try..except block prints, confirming that execution continued normally past the whole try...except structure. …
Drawn by us to help you understand the concept clearly, and verified to make sure it's accurate. For exams, practice from your NCERT textbook's own diagram.
This is the same script as Figure 1.9, Program 1-2, run again — but this time the user enters 0 when prompted for the denominator. The program again starts with Practicing for try block and the prompt Enter the denominator, but this time the division inside the try block fails: dividing by zero raises a ZeroDivisionError.
Because the script wrapped that risky division in a try...except block written specifically to catch ZeroDivisionError, the exception does not crash the program or print a traceback at all. Instead, the matching except block runs and prints its own custom message: Denominator as ZERO.... not allowed. Execution then continues normally to OUTSIDE try..except block, exactly as it did in the error-free run. …
Drawn by us to help you understand the concept clearly, and verified to make sure it's accurate. For exams, practice from your NCERT textbook's own diagram.
This is the output of Program 1-4, a script that also guards a division with try...except, but this time using a bare except — one written without naming a specific exception class — run with a zero denominator. After RESTART:, the program prints Handling exceptions without naming them, prompts for the denominator, and the user enters 0. As before, dividing by zero raises a ZeroDivisionError inside the try block.
Because this script's except clause does not specify which exception to catch, it catches any exception that occurs in the try block — including this ZeroDivisionError — and prints its generic message: OOPS.....SOME EXCEPTION RAISED (note the message is shown exactly as printed, with a leading space). …