Python Try Except

Last Updated : 8 Jun, 2026

Errors and exceptions can interrupt the normal flow of a program during execution. Python provides try and except blocks to handle such errors gracefully without stopping the entire program. When an error occurs inside the try block, Python transfers control to the except block, allowing the program to handle the error safely.

  • Prevents the program from crashing due to runtime errors.
  • Handles common errors like division by zero or invalid input.
  • Displays meaningful error messages and improves program reliability.

Example: The below example handles a division by zero error using try and except.

Python
try:
    x = 10 / 0
    print(x)
except:
    print("An exception occurred.")

Output
An exception occurred.

Explanation: The statement 10 / 0 raises a division by zero error inside the try block. Python stops executing the remaining code in try and moves to the except block, which prints the error message.

Syntax

try:
# Code that may raise an exception
except:
# Code to handle the exception

Parameters:

  • try: Contains the code that may generate an error.
  • except: Contains the code that executes if an exception occurs in the try block.

Working of try-except Blocks

  • The code inside the try block executes first.
  • If no error occurs, the except block is skipped.
  • If an error occurs inside the try block, Python immediately jumps to the except block.
  • If the error is not handled, the program stops and displays the error message.
  • A try statement can contain multiple except blocks to handle different types of errors.

Common Exception Errors

  • ZeroDivisionError: Raised when dividing a number by zero.
  • ValueError: Raised when a function receives an invalid value.
  • TypeError: Raised when an operation is performed on incompatible data types.
  • FileNotFoundError: Raised when a file does not exist.
  • ImportError: Raised when Python cannot import a module.

Examples

Example 1: In this example, the code inside the try block runs successfully because no exception occurs. The except block is skipped.

Python
def divide(x, y):
    try:
        result = x // y
        print("Result:", result)
    except ZeroDivisionError:
        print("Cannot divide by zero")

divide(10, 2)

Output
Result: 5

Explanation: Since 10 // 2 is valid, the try block executes normally and prints the result.

Example 2: This example shows how except handles an error when dividing by zero.

Python
def divide(x, y):
    try:
        result = x // y
        print("Result:", result)
    except ZeroDivisionError:
        print("Cannot divide by zero")

divide(10, 0)

Output
Cannot divide by zero

Explanation: 10 // 0 raises a ZeroDivisionError, so Python jumps to the except ZeroDivisionError block.

Example 3: This example uses Exception as e to display the actual error message generated by Python.

Python
def divide(x, y):
    try:
        result = x // y
        print("Result:", result)
    except Exception as e:
        print("Error:", e)

divide(10, "2")
divide(10, 0)

Output
Error: unsupported operand type(s) for //: 'int' and 'str'
Error: integer division or modulo by zero

Explanation: The first call causes a type error because "2" is a string. The second call raises a division by zero error. Both are caught using Exception as e.

Else Clause

else block is used with try-except and executes only when no exception occurs in the try block. If an exception is raised, the else block is skipped.

Syntax:

try:
# Code that may raise an exception
except:
# Runs if an exception occurs
else:
# Runs if no exception occurs

Example: In this example, the else block runs only when the division operation is successful.

Python
def divide(a, b):
    try:
        result = a // b
    except ZeroDivisionError:
        print("Cannot divide by zero")
    else:
        print("Result:", result)

divide(10, 2)
divide(10, 0)

Output
Result: 5
Cannot divide by zero

Explanation:

  • For divide(10, 2), no exception occurs, so the else block executes and prints the result.
  • For divide(10, 0), a ZeroDivisionError occurs, so the except block runs instead.

Finally Keyword

finally block is always executed after the try and except blocks, whether an exception occurs or not. It is commonly used for cleanup tasks such as closing files or releasing resources.

Syntax:

try:
# Code that may raise an exception
except:
# Runs if an exception occurs
else:
# Runs if no exception occurs
finally:
# Always executed

Example: In this example, the finally block executes even though a division by zero error occurs.

Python
try:
    result = 10 // 0
    print(result)

except ZeroDivisionError:
    print("Cannot divide by zero")

finally:
    print("This block always executes")

Output
Cannot divide by zero
This block always executes

Explanation: 10 // 0 raises a ZeroDivisionError, so the except block runs. After that, the finally block executes regardless of the exception.

Nested Try-Except Blocks

Python allows one try-except block to be placed inside another try-except block. This is called a nested try-except block and is useful when different sections of code may raise different exceptions.

Example: In this example, the outer block handles division errors, while the inner block handles list index errors.

Python
def divide_and_access(a, b):
    try:
        result = a // b
        print("Result:", result)

        try:
            nums = [1, 2, 3]
            print(nums[5])

        except IndexError:
            print("Invalid index access")

    except ZeroDivisionError:
        print("Cannot divide by zero")

    finally:
        print("Execution completed")

divide_and_access(6, 2)
print("---")
divide_and_access(6, 0)

Output
Result: 3
Invalid index access
Execution completed
---
Cannot divide by zero
Execution completed

Explanation:

  • The inner try-except block handles the IndexError caused by accessing an invalid list index.
  • The outer try-except block handles the ZeroDivisionError when dividing by zero.
  • The finally block runs in both cases.
Comment