Skip to content

Mastering Python Exception Handling with Try, Except, Else, and Finally


Exception handling is a crucial aspect of programming in Python, as it allows you to gracefully handle errors and unexpected situations in your code. Python provides a powerful mechanism for this through the Try, Except, Else, and Finally blocks. In this tutorial, we’ll explore these blocks and learn how to use them effectively.

The Try Block

The try block is where you place the code that might raise an exception. It is the section of code you want to monitor for errors. Here’s an example:

    result = 10 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError:
    print("Division by zero is not allowed.")

In this example, the try block attempts to divide 10 by 0, which raises a ZeroDivisionError. The except block catches this exception and prints an error message.

The Except Block

The except block is where you handle exceptions. You can specify the type of exception you want to catch or use a general except block to catch all exceptions.

    result = 10 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed.")
except Exception as e:
    print(f"An error occurred: {e}")

In this code, the except block catches the ZeroDivisionError first and prints a specific message. If any other exception occurs, it will be caught by the general except block, which provides a more generic error message.

The Else Block

The else block is executed when no exceptions are raised in the try block. It is used for code that should run only if the try block executes successfully.

    result = 10 / 2  # No exception is raised
except ZeroDivisionError:
    print("Division by zero is not allowed.")
    print(f"Result: {result}")

In this example, since there are no exceptions, the else block prints the result.

The Finally Block

The finally block is used to execute code regardless of whether an exception is raised or not. It’s often used for cleanup operations, like closing files or releasing resources. With the below example, you can understand this.

    file = open("example.txt", "r")
    data =
except FileNotFoundError:
    print("File not found.")
    file.close()  # This will always be executed, even if an exception occurs

In this code, the finally block ensures that the file is closed, whether an exception occurs or not.

Mastering the try, except, else, and finally blocks in Python is essential for writing robust and error-free code. These blocks give you fine-grained control over how your program responds to different situations, making your code more reliable and maintainable.

Try the below exercises.

[ays_quiz id=’1′]

Exercise 1: File Reading

Create a program that prompts the user for a filename. Try to open and read the file. Handle the FileNotFoundError exception if the file does not exist. Use the try, except, and else blocks to display the content of the file if it exists and an error message if the file is not found.

Exercise 2: Password Validation

Write a program that asks the user to enter a password. Check if the password meets the following criteria:

  • At least 8 characters long.
  • Contains at least one uppercase letter.
  • Contains at least one lowercase letter.
  • Contains at least one digit. Handle any validation errors using appropriate exceptions and provide error messages for each validation rule. Use the try, except, and else blocks to inform the user whether their password is valid.

Exercise 3: File Writing

Create a program that asks the user for a filename and some text to write to the file. Handle any potential exceptions when writing to the file, such as PermissionError. Use the try, except, and else blocks to confirm that the file was written successfully or display an error message if an exception occurs.

Exercise 4: Resource Cleanup

Write a program that simulates opening and closing a resource (e.g., a database connection, network socket, or file). Use the try and finally blocks to ensure that the resource is properly closed even if an exception occurs during the operation.

Exercise 5: Custom Exception

Create a custom exception class (e.g., InvalidInputError) and use it in a program. Write a program that asks the user to enter an age, and if the age is less than 0 or greater than 120, raise the custom exception. Handle the custom exception using the try and except blocks to display an error message.

These exercises will help you improve your exception-handling skills in Python and ensure that you can handle various error scenarios effectively. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *