Nearby lessons

79 of 159

Python - Try Except

📌 What You Will Learn
  • 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

🐍Code Cell
1try:
2 Risky Code
3 
4except XXX:
5 Handling Code / Alternative Code
Output
No output captured.

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 except block 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

🐍Code Cell
1try:
Output
No output captured.

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.

🐍Code Cell
1try:
2 print(10/0)
Output
No output captured.

The except Block

🐍Code Cell
1except XXX:
Output
No output captured.

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

🐍Code Cell
1try:
2 print(10/0)
3 
4except ZeroDivisionError:
5 print("Alternative Code Executed")
Output
Alternative Code Executed

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

🐍Code Cell
1print("stmt-1")
2 
3print(10/0)
4 
5print("stmt-3")
Output
stmt-1

Traceback (most recent call last):
  File "test.py", line 2, in 
    print(10/0)

ZeroDivisionError: division by zero

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

🐍Code Cell
1print("stmt-1")
2 
3try:
4 print(10/0)
5 
6except ZeroDivisionError:
7 print(10/2)
8 
9print("stmt-3")
Output
stmt-1
5.0
stmt-3

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.

🐍Code Cell
1try:
2 stmt-1
3 stmt-2
4 stmt-3
5 
6except XXX:
7 stmt-4
8 
9stmt-5
Output
No output captured.

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

  1. If no exception occurs, the except block is skipped.
  2. If a matching except block exists, the exception is handled and the remaining program continues.
  3. If no matching except block exists, abnormal termination occurs.
  4. If another exception occurs inside the except block, 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

🐍Code Cell
1except ExceptionType as msg:
2 statements
Output
No output captured.

Explanation

  • ExceptionType represents the type of exception to be handled.
  • msg is the exception object, which stores the description of the raised exception.
  • We can print this object to display the exact error message.

Program

🐍Code Cell
1try:
2 print(10/0)
3 
4except ZeroDivisionError as msg:
5 print("exception raised and its description is:", msg)
Output
exception raised and its description is: division by zero

Key Points

  • Every raised exception has an associated exception object.
  • The syntax except ExceptionType as msg stores the exception object inside msg.
  • The exception object can be printed directly to show the error description.
📝 Key Takeaways
  • 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

🧠 Test Your Knowledge

10 Questions
Progress: 0 / 10