Exceptions#

Overview#

Exception is a mechanism to catch and handle errors in your codes. When an exception occurs, Python will normally stop and generate an error message. But, the expection handling can deal with the error proposing an alternative direction on your program.

In simple words:

  • try block lets you test a block of code for errors.

  • except block lets you handle the error.

  • else block lets you execute code when there is no error.

  • finally block lets you execute code, regardless of the result of the try- and except blocks.

General syntax

try:
    # Code that may raise an exception
    # ...
except:
    # Code to handle the exception of type ExceptionType1
    # ...
else:
    # Code to execute if no exception occurred
    # ...
finally:
    # Code that will always execute, regardless of whether an exception occurred or not
    # ...

Example#

Let’s create a try/except code with errors

# Example 1
try:
    x = 10 / 0  # Division by zero raises a ZeroDivisionError
    print(x)  # This line is skipped
except ZeroDivisionError:
    print("Error: Division by zero")
else:
    print("No exception occurred")
finally:
    print("Finally block executed")
Error: Division by zero
Finally block executed
# Example 2

def validate_student_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative.")
    elif age < 18:
        raise ValueError("You must be at least 18 years old.")
    else:
        print("Age is valid.")

user_age = 20
try:
    validate_student_age(user_age)
except ValueError as e:
    print("Invalid age:", str(e))
else:
    print("Age verification successful.")
finally:
    print("Age validation completed.")
Age is valid.
Age verification successful.
Age validation completed.