Nearby lessons
79 of 159Python - Try Except
- Place risky code inside the try block and handling code inside the except block
- Compare abnormal termination without try-except with graceful termination using try-except
- Print exception information by using the exception object with except ExceptionType as msg
- Trace the control flow of try-except in all four cases
Customized Exception Handling using try-except
It is highly recommended to handle exceptions.
The code which may raise an exception is called Risky Code.
We have to place the risky code inside the try block, and the corresponding handling code should be placed inside the except block.
General Syntax
Explanation
The try-except statement is used to handle runtime exceptions.
The program first executes the statements inside the try block.
- If no exception occurs, the
exceptblock is skipped. - If an exception occurs, Python checks whether the exception matches the specified exception type. If it matches, the corresponding handling code is executed.
The try Block
Explanation
The try block contains the code that may raise an exception.
Only those statements which may raise an exception should be placed inside the try block.
The except Block
Explanation
The except block contains the exception handling code.
If an exception occurs inside the try block and it matches the specified exception type, then the statements inside the except block are executed.
The code inside the except block is also called Alternative Code.
Conceptual Example
Explanation
The risky statement raises a ZeroDivisionError.
Since the exception type matches the except ZeroDivisionError block, Python executes the alternative code instead of terminating the program immediately.
Execution Flow
Program Starts
│
▼
Execute try Block
│
▼
Exception Raised?
┌────┴────┐
│ │
No Yes
│ │
▼ ▼
Continue Find Matching
Program except Block
│
┌──────┴──────┐
│ │
▼ ▼
Match No Match
│ │
▼ ▼
Execute Handling Abnormal
Code Termination
│
▼
Continue Remaining Program
Advantages of try-except
- Handles Runtime Exceptions.
- Prevents abnormal program termination.
- Provides an alternative solution.
- Allows the remaining part of the program to execute normally.
- Helps achieve Graceful Termination.
Exception Handling without try-except
If we do not use the try-except block, then whenever an exception occurs, the Python Interpreter terminates the program abnormally.
Since there is no exception handling code available, the remaining statements of the program are not executed. This is called Abnormal Termination or Non-Graceful Termination.
Program
Result
Abnormal Termination
(Non-Graceful Termination)
Explanation
stmt-1 executes successfully.
print(10/0) raises a ZeroDivisionError. Since no handling code is available, the interpreter immediately terminates the program.
stmt-3 is never executed.
Exception Handling with try-except
If the risky code is placed inside the try block and the handling code is placed inside the except block, then Python can handle the exception and continue executing the remaining program.
This is called Graceful Termination.
Program
Result
Normal Termination
(Graceful Termination)
Explanation
stmt-1 executes successfully.
The risky statement inside the try block raises a ZeroDivisionError. Instead of terminating the program immediately, Python searches for a matching except block.
The raised exception matches ZeroDivisionError, so print(10/2) executes as an alternative solution and prints 5.0.
Since the exception has been handled successfully, stmt-3 executes normally.
Difference in Execution
| Without try-except | With try-except |
|---|---|
| Exception is not handled. | Exception is handled. |
| Program stops immediately. | Program continues execution. |
| Remaining statements are skipped. | Remaining statements are executed. |
| Abnormal termination. | Normal (Graceful) termination. |
Control Flow in try-except
The execution of a try-except block depends on whether an exception occurs inside the try block and whether a matching except block is available.
Possible Cases
| Case | Execution Flow | Result |
|---|---|---|
| Case 1 - No exception | 1 → 2 → 3 → 5 | Normal Termination |
| Case 2 - Exception at stmt-2, matching except available | 1 → 4 → 5 | Normal Termination |
| Case 3 - Exception at stmt-2, no matching except | 1 → Abnormal Termination | Abnormal Termination |
| Case 4 - Exception raised inside the except block | 1 → 4 → Abnormal Termination | Abnormal Termination |
General Control Flow
Program Starts
│
▼
Execute try Block
│
┌───────────┴───────────┐
│ │
▼ ▼
No Exception Exception Raised
│ │
▼ ▼
Skip except Block Search Matching except
│ │
│ ┌────────┴────────┐
│ │ │
▼ ▼ ▼
stmt-5 Match Found No Match
│ │ │
▼ ▼ ▼
Normal Termination Execute stmt-4 Abnormal Termination
│
▼
Execute stmt-5
│
▼
Normal Termination
Key Points
- If no exception occurs, the
exceptblock is skipped. - If a matching
exceptblock exists, the exception is handled and the remaining program continues. - If no matching
exceptblock exists, abnormal termination occurs. - If another exception occurs inside the
exceptblock, abnormal termination occurs.
How to Print Exception Information
We can print the exception information by using the exception object inside the except block.
Instead of simply handling the exception, we can also display the actual exception description generated by Python.
Syntax
Explanation
ExceptionTyperepresents the type of exception to be handled.msgis the exception object, which stores the description of the raised exception.- We can print this object to display the exact error message.
Program
Key Points
- Every raised exception has an associated exception object.
- The syntax
except ExceptionType as msgstores the exception object insidemsg. - The exception object can be printed directly to show the error description.
- The try block contains risky code, and the except block contains the handling or alternative code
- Without try-except, an unhandled exception terminates the program abnormally
- With a matching except block, the exception is handled and the remaining program continues - graceful termination
- except ExceptionType as msg stores the exception object, which holds the error description
- The except block runs only when a matching exception occurs