Python try-except-finally Explained with Examples

In Python, the try, except, and finally blocks are used to handle exceptions and ensure that certain code is executed regardless of whether an exception was raised or not.

Syntax

try:
    # Code that may raise an exception
    # ...
except ExceptionType as e:
    # Code to handle the exception
    # ...
finally:
    # Cleanup code that will always execute
    # ...

Try Block

The try block contains the code that might raise an exception. If an exception occurs within this block, the execution jumps to the except block(s).

Except Block

The except block is used to catch and handle exceptions. You can have multiple except blocks to catch different types of exceptions. If no exception type is specified, it catches all exceptions.

Finally Block

The finally block is optional and is used to execute code that must run regardless of whether an exception was raised or not. This is typically used for cleanup operations, such as closing files or releasing resources.

Examples

Basic Try-Except

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

In this example, attempting to divide by zero raises a ZeroDivisionError, which is caught and handled by the except block.

Multiple Except Blocks

try:
    x = int(input("Enter a number: "))
    y = 10 / x
except ValueError:
    print("Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero!")

Here, the code attempts to convert user input to an integer and divide 10 by it. If the input is not a number, a ValueError is raised and caught. If the input is zero, a ZeroDivisionError is raised and caught.

Finally Block

try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found.")
finally:
    file.close()
    print("File closed.")

In this example, the code attempts to open and read a file. If the file does not exist, a FileNotFoundError is raised and caught. Regardless of whether an exception occurs, the finally block ensures that the file is closed.

Catching All Exceptions

try:
    # Some code that might raise an exception
except:
    print("An exception occurred.")

This is generally not recommended as it can catch unexpected exceptions that you might want to handle differently. It’s better to catch specific exceptions.

Raising Exceptions

try:
    raise ValueError("This is a custom error message.")
except ValueError as e:
    print(e)

In this example, a ValueError is intentionally raised and caught. The error message is printed.