[Python OOP] 6. Error Handling and Exceptions in OOP

07 Nov 2023 By Code Bricks

6. Error Handling and Exceptions in OOP

Effective error handling is critical in programming to ensure the robustness of the application. In this section, we’ll cover how to create custom exception classes, handle exceptions, and raise exceptions within object-oriented Python.

6.1 Custom Exception Classes

Custom exceptions allow you to create meaningful exception types specific to your application’s domain.

class Error(Exception):
    """Base class for other exceptions"""
    pass

class ValueTooSmallError(Error):
    """Raised when the input value is too small"""
    pass

class ValueTooLargeError(Error):
    """Raised when the input value is too large"""
    pass

# Usage
def check_value(value):
    if value < 10:
        raise ValueTooSmallError
    elif value > 100:
        raise ValueTooLargeError

try:
    check_value(1)
except ValueTooSmallError:
    print("This value is too small!")
except ValueTooLargeError:
    print("This value is too large!")

6.2 Handling Exceptions in OOP

Handling exceptions in methods and constructors ensures that your object maintains a valid state even when an error occurs.

class DataStore:
    def __init__(self, data_file):
        try:
            self.file = open(data_file)
        except IOError:
            print("An error occurred trying to read the file.")
    
    def read_data(self):
        try:
            return self.file.read()
        except IOError:
            print("An error occurred trying to read the file.")
        finally:
            self.file.close()

# Usage
store = DataStore('non_existent_file.txt')
data = store.read_data()

6.3 Raising Exceptions in Methods

Methods can raise exceptions to signal that they were unable to complete their intended task.

class UserProfile:
    def __init__(self, username, age):
        self.username = username
        if age < 0:
            raise ValueError("Age cannot be negative.")
        self.age = age

    def set_age(self, new_age):
        if new_age < 0:
            raise ValueError("Age cannot be negative.")
        self.age = new_age

# Usage
try:
    user = UserProfile("john_doe", -1)
except ValueError as e:
    print(e)  # Output: Age cannot be negative.

try:
    user = UserProfile("john_doe", 25)
    user.set_age(-20)
except ValueError as e:
    print(e)  # Output: Age cannot be negative.

Exception handling in OOP involves using try-except blocks, custom exception classes, and the raise statement within methods to maintain the integrity and reliability of the code.