Open Category List

Exception Handling

1 minuteread

Exceptions are errors detected during execution. Python provides a way to handle exceptions using try, except, else, and finally blocks.

Basic Exception Handling:

try:
    # Code that might raise an exception
    result = 10 / 0
except ZeroDivisionError:
    # Code to handle the exception
    print("Error: Division by zero is not allowed.")

Handling Multiple Exceptions:

try:
    # Code that might raise an exception
    num = int(input("Enter a number: "))
    result = 10 / num
except ValueError:
    print("Error: Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")
else:
    # Executes if no exceptions occur
    print(f"Result is {result}")
finally:
    # Executes regardless of exceptions
    print("Execution complete.")

Raising Exceptions:

def divide(a, b):
    if b == 0:
        raise ValueError("Argument 'b' must not be zero.")
    return a / b

try:
    divide(10, 0)
except ValueError as e:
    print(e)

Related Knowledge Base Posts