How to use the Try and Except statement in Python

1 min

In Python, the try and except statement allows you to handle errors and exceptions in your code in a clean and organised way. The try block contains the code that might raise an exception, and the except block contains the code that will be executed if an exception is raised.

Here's an example of how you can use the try and except statement to handle a ZeroDivisionError:

try:
    x = 5 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")

In this example, the code in the try block attempts to divide 5 by 0 which raises a ZeroDivisionError. The code in the except block then runs, and the message "You can't divide by zero!" is printed.

You can also use the finally block to specify code that should be executed no matter if an exception is raised or not.

try:
    x = 5 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")
finally:
    print("This will run no matter what.")

You can also use the else block to specify code that should be executed if an exception is not raised.

try:
    x = 5 / 2
except ZeroDivisionError:
    print("You can't divide by zero!")
else:
    print(f"The result is {x}")

You can also use raise statement to raise an exception explicitly

def raise_exception():
    raise Exception("This is an exception")
try:
    raise_exception()
except Exception as e:
    print(e)

It's worth noting that try and except statements can be nested, you can also use as keyword to assign an exception to a variable and use it later, also you can use multiple except blocks to handle different types of exceptions.