Python Exception Handling Tutorial

Introduction

Exception handling in Python is a mechanism to handle runtime errors, ensuring the normal flow of the program. When an error occurs, Python generates an exception, which can be handled to prevent the program from crashing. This tutorial covers how to handle exceptions in Python using the try, except, else, and finally blocks, along with raising exceptions and defining custom exceptions.

Table of Contents

  1. What is an Exception?
  2. Handling Exceptions
  3. Multiple Exceptions
  4. Else Clause
  5. Finally Clause
  6. Raising Exceptions
  7. Custom Exceptions
  8. Conclusion

1. What is an Exception?

An exception is an event that disrupts the normal flow of the program. Examples of exceptions include dividing by zero, accessing an undefined variable, and file not found errors. Python provides a way to handle these exceptions to maintain the program's flow.

2. Handling Exceptions

The try block lets you test a block of code for errors. The except block lets you handle the error.

Example

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

print("Program continues...")  # Output: Cannot divide by zero
                                #         Program continues...

3. Multiple Exceptions

You can catch multiple exceptions using multiple except blocks or a single except block handling multiple exceptions.

Example

try:
    x = int(input("Enter a number: "))
    result = 10 / x
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Invalid input, please enter a number")

print("Program continues...")

Example with Single except Block

try:
    x = int(input("Enter a number: "))
    result = 10 / x
except (ZeroDivisionError, ValueError) as e:
    print(f"Error occurred: {e}")

print("Program continues...")

4. Else Clause

The else block is executed if no exceptions are raised in the try block.

Example

try:
    x = int(input("Enter a number: "))
    result = 10 / x
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Invalid input, please enter a number")
else:
    print(f"Result is {result}")

print("Program continues...")

5. Finally Clause

The finally block is executed no matter if an exception is raised or not. It is useful for cleaning up resources, such as closing files.

Example

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

print("Program continues...")

6. Raising Exceptions

You can raise an exception using the raise keyword.

Example

def check_age(age):
    if age < 18:
        raise ValueError("Age must be 18 or above")
    return "Age is valid"

try:
    print(check_age(15))
except ValueError as e:
    print(e)  # Output: Age must be 18 or above

7. Custom Exceptions

You can define your own exceptions by creating a new class that inherits from the built-in Exception class.

Example

class CustomError(Exception):
    def __init__(self, message):
        self.message = message

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

Example: Real-World Scenario

class InsufficientFundsError(Exception):
    def __init__(self, message="Insufficient funds"):
        self.message = message
        super().__init__(self.message)

class BankAccount:
    def __init__(self, balance):
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise InsufficientFundsError("Insufficient funds for withdrawal")
        self.balance -= amount
        return self.balance

# Creating a bank account object
account = BankAccount(1000)

try:
    print(account.withdraw(1500))
except InsufficientFundsError as e:
    print(e)  # Output: Insufficient funds for withdrawal

Conclusion

Exception handling is an essential part of writing robust and error-free code. By understanding how to handle exceptions using try, except, else, and finally blocks, and by raising and defining custom exceptions, you can ensure that your Python programs handle errors gracefully and continue to run smoothly. This tutorial covered the basics of exception handling in Python with various examples to help you get started.

Comments