Python Exceptions

In Python, an exception is an event that disrupts the normal flow of a program's execution. When a Python script encounters a situation it cannot handle, it raises an exception. This may occur due to various reasons like division by zero, file not found, invalid syntax, etc. Exceptions are Python objects that represent errors.

Handling Exceptions using try-except

Python provides a way to handle exceptions using a try block followed by one or more except blocks. This prevents your program from crashing and allows you to handle errors gracefully.

Examples

1. Handling Division by Zero


try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Division by zero is not allowed!")
            

Output

Error: Division by zero is not allowed!

Handling Multiple Exceptions

You can handle multiple exceptions by specifying different except blocks for different types of exceptions. If you want to handle multiple exceptions in a single block, you can use a tuple of exception types.

2. Handling Multiple Exceptions


try:
    value = int("abc")
    result = 10 / value
except ValueError:
    print("Error: Invalid input, please enter a number!")
except ZeroDivisionError:
    print("Error: Division by zero is not allowed!")
            

Output

Error: Invalid input, please enter a number!

The else and finally Clauses

Python's try block can have an optional else block and a finally block:

3. Using else and finally


try:
    num = int(input("Enter a number: "))
    print("You entered:", num)
except ValueError:
    print("Error: Invalid number!")
else:
    print("No exceptions were raised.")
finally:
    print("Execution complete.")
            

Output

Enter a number: (User Input) You entered: (User Input) No exceptions were raised. Execution complete.

Raising Exceptions

You can raise exceptions in your code using the raise keyword. This is useful when you want to enforce certain conditions in your program.

4. Raising an Exception


def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative!")
    return age

try:
    print(check_age(-5))
except ValueError as e:
    print("Error:", e)
            

Output

Error: Age cannot be negative!

Creating Custom Exceptions

Python allows you to create your own exceptions by extending the Exception class. This is useful for creating meaningful error messages specific to your application.

5. Custom Exception


class NegativeNumberError(Exception):
    pass

def check_positive(number):
    if number < 0:
        raise NegativeNumberError("Negative numbers are not allowed!")
    return number

try:
    print(check_positive(-10))
except NegativeNumberError as e:
    print("Error:", e)
            

Output

Error: Negative numbers are not allowed!

Exception handling is a crucial aspect of Python programming, enabling you to manage errors gracefully without crashing your programs. By using try, except, else, and finally blocks, you can handle exceptions effectively. Additionally, creating custom exceptions can help you enforce specific conditions and provide meaningful error messages.