Skip to Content
Course content

In Python, the try-except block is used to catch and handle exceptions (errors) that may occur during the execution of a program. By using try-except blocks, we can prevent the program from crashing due to errors and provide a more graceful way to handle issues.

Basic Structure of try-except Block

try:
    # Code that might raise an exception
    result = 10 / 0
except ZeroDivisionError:
    # Handling the exception
    print("Cannot divide by zero!")

In this example:

  • The code inside the try block raises a ZeroDivisionError (dividing by zero).
  • The exception is caught by the except ZeroDivisionError block, and a message is printed instead of the program crashing.

Components of try-except Block

  1. try Block:
    • The code that is placed inside the try block is the code that may potentially raise an exception.
    • If no exception occurs, the code in the except block is skipped, and the program continues running normally.
  2. except Block:
    • The except block handles the exception raised in the try block.
    • We can specify different types of exceptions to handle specific errors (e.g., ZeroDivisionError, ValueError).
    • If the exception matches the one specified in the except block, the code inside the except block is executed.

Catching Multiple Exceptions

You can handle multiple types of exceptions with separate except blocks, or catch multiple exceptions in a single block.

1. Handling Multiple Exceptions with Separate except Blocks:

try:
    x = int(input("Enter a number: "))
    result = 10 / x
except ValueError:
    print("Invalid input. Please enter a valid number.")
except ZeroDivisionError:
    print("Cannot divide by zero!")
  • If the user enters a non-numeric value, a ValueError will be raised.
  • If the user enters 0, a ZeroDivisionError will be raised.

2. Handling Multiple Exceptions with a Single except Block:

try:
    x = int(input("Enter a number: "))
    result = 10 / x
except (ValueError, ZeroDivisionError) as e:
    print(f"Error occurred: {e}")
  • Both ValueError and ZeroDivisionError are handled in the same block. The as e syntax captures the exception message, which can be printed.

The else Block

The else block can be used to specify code that should be executed only if no exception occurs in the try block.

try:
    x = int(input("Enter a number: "))
    result = 10 / x
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input. Please enter a valid number.")
else:
    print(f"Result is: {result}")
  • If there are no exceptions, the else block will run and print the result.

The finally Block

The finally block is used to specify code that will be executed no matter what, whether an exception occurred or not. It’s often used for cleanup actions, such as closing files or releasing resources.

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found!")
finally:
    print("Closing the file.")
    file.close()
  • The finally block will run after the try block (and except block if an exception occurs).
  • Even if the FileNotFoundError occurs, the finally block ensures that the file is closed.

Raising Exceptions Explicitly

You can also raise exceptions explicitly using the raise keyword. This can be useful for raising custom exceptions or for re-throwing an existing exception.

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero!")
    return a / b

try:
    result = divide(10, 0)
except ValueError as e:
    print(e)

In this case, a ValueError is raised manually if the denominator b is zero.

Summary of try-except Block

  • try: Executes the code that might raise an exception.
  • except: Handles the exception if one is raised in the try block.
  • else: Optionally runs code if no exception occurs.
  • finally: Executes code that needs to run regardless of whether an exception occurred.

Example: Handling Multiple Types of Exceptions

try:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
except ValueError:
    print("Invalid input! Please enter integers.")
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print(f"The result is: {result}")
finally:
    print("Execution complete.")

In this example:

  • If a user inputs a non-integer value, a ValueError is raised.
  • If the user tries to divide by zero, a ZeroDivisionError is raised.
  • The else block prints the result if no exception occurs.
  • The finally block prints a message indicating the end of execution.

Commenting is not enabled on this course.