Exception Handling

Exception handling in Python allows you to gracefully handle errors that may occur during the execution of a program. This tutorial provides an overview of Python exception handling, including try-except blocks, handling specific exceptions, and using the finally block.

Handling Exceptions with Try-Except

To handle exceptions in Python, you can use the try-except block. Code that might raise an exception is placed inside the try block, and the except block catches and handles the exception if it occurs.


      try:
          # Code that may raise an exception
          result = 10 / 0
      except:
          # Code to handle the exception
          print("An error occurred.")
      

Handling Specific Exceptions

You can specify the type of exception to catch and handle different types of errors differently.


      try:
          # Code that may raise an exception
          num1 = int(input("Enter a number: "))
          num2 = int(input("Enter another number: "))
          result = num1 / num2
      except ZeroDivisionError:
          # Handling division by zero error
          print("Division by zero is not allowed.")
      except ValueError:
          # Handling invalid input error
          print("Invalid input. Please enter valid numbers.")
      

Handling Multiple Exceptions

You can handle multiple exceptions in a single try-except block.


      try:
          # Code that may raise an exception
          age = int(input("Enter your age: "))
          result = 100 / age
      except ZeroDivisionError:
          print("Division by zero is not allowed.")
      except ValueError:
          print("Invalid age. Please enter a valid number.")
      except Exception as e:
          # Catching any other unexpected exceptions
          print("An unexpected error occurred:", e)
      

Using the Finally Block

The finally block is used to execute code regardless of whether an exception occurs or not. It is executed after the try and except blocks, whether an exception is raised or not.


      try:
          # Code that may raise an exception
          file = open("data.txt", 'r')
          content = file.read()
          print(content)
      except FileNotFoundError:
          print("File not found.")
      finally:
          # Code to execute regardless of an exception
          file.close()
      

Raising Exceptions

You can raise custom exceptions using the raise keyword.


      try:
          age = int(input("Enter your age: "))
          if age < 0:
              raise ValueError("Age cannot be negative.")
      except ValueError as ve:
          print("Error:", ve)