Python Error and Exception Handling : Raising Exceptions

Learn Python @ Freshers.in

Exception handling in Python is not just about handling errors that occur naturally. You can also take control of the exception system by raising your own exceptions when certain conditions are met. In this in-depth guide, we’ll explore the concept of raising exceptions in Python, complete with real-world examples and their outputs.

What Are Custom Exceptions?

Custom exceptions, also known as user-defined exceptions, allow you to create your own exception classes. These exceptions are useful when you want to handle specific error scenarios within your code.

Raising Exceptions with raise

In Python, you can raise an exception using the raise statement. The general syntax is as follows:

raise ExceptionType("Error message")

Let’s illustrate this with a real-world example. Suppose you are building a function that calculates the area of a rectangle but want to raise a custom exception if the dimensions provided are invalid.

class InvalidDimensionsError(Exception):
    def __init__(self, message):
        super().__init__(message)

def calculate_rectangle_area(length, width):
    if length <= 0 or width <= 0:
        raise InvalidDimensionsError("Invalid dimensions. Length and width must be positive.")
    return length * width

try:
    area = calculate_rectangle_area(-5, 4)
except InvalidDimensionsError as e:
    print("Error:", e)
else:
    print("Area:", area)

Output:

Error: Invalid dimensions. Length and width must be positive.

In this example, we raise a custom exception InvalidDimensionsError with a descriptive error message when the provided dimensions are not valid.

Custom Exception Hierarchy

It’s common to create a hierarchy of custom exceptions to handle various error scenarios more effectively. Here’s an example:

class CustomError(Exception):
    pass

class SpecificError1(CustomError):
    pass

class SpecificError2(CustomError):
    pass

try:
    # Code that may raise SpecificError1 or SpecificError2
except SpecificError1:
    # Handle SpecificError1
except SpecificError2:
    # Handle SpecificError2
except CustomError:
    # Handle other custom errors

When to Raise Exceptions?

You should consider raising exceptions when:

  1. You encounter exceptional cases that your code cannot handle gracefully.
  2. You want to provide clear and descriptive error messages to aid debugging.
  3. You want to differentiate between various types of errors for precise error handling.

Example

Let’s explore a real-world example of raising custom exceptions:

Suppose you are developing a banking application and want to raise an exception when a user tries to withdraw more money than their account balance allows.

class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Insufficient funds. Current balance: {balance}, Withdrawal amount: {amount}")

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(balance, amount)
    return balance - amount

try:
    account_balance = 1000
    withdrawal_amount = 1500
    new_balance = withdraw(account_balance, withdrawal_amount)
except InsufficientFundsError as e:
    print("Error:", e)
else:
    print("Withdrawal successful. New balance:", new_balance)

Output:

Error: Insufficient funds. Current balance: 1000, Withdrawal amount: 1500

In this example, we raise the InsufficientFundsError exception when the withdrawal amount exceeds the account balance, providing valuable information about the error.

Author: user