Skip to main content

Python Custom exceptions

Custom exceptions in Python allow you to create specific error types that can provide more informative error handling and make your code more readable and maintainable. You can define custom exceptions by creating new classes that inherit from the built-in Exception class or any of its subclasses.

Creating a Custom Exception

Here’s how you can create a basic custom exception:

class MyCustomError(Exception): """Custom exception class for specific errors.""" pass

Using Custom Exceptions

Once you have defined a custom exception, you can use it in your code by raising it with the raise statement and catching it with a try-except block.

Example:

class NegativeNumberError(Exception):
    """Exception raised for errors in the input if the number is negative."""
    def __init__(self, value):
        self.value = value
        self.message = f"NegativeNumberError: {value} is not a positive number."
        super().__init__(self.message)

def check_positive(number):
    if number < 0:
        raise NegativeNumberError(number)
    return number

try:
    check_positive(-5)
except NegativeNumberError as e:
    print(e)

In this example:

  • NegativeNumberError is a custom exception that includes an __init__ method to store the invalid value and a custom error message.
  • The check_positive function raises a NegativeNumberError if the input number is negative.
  • The try block attempts to check a negative number, and the except block catches the NegativeNumberError and prints its message.

Custom Exception Hierarchies

You can create a hierarchy of custom exceptions by defining multiple custom exception classes, which can be useful for categorizing different types of errors.

Example:

class ApplicationError(Exception):
    """Base class for other exceptions in this module."""
    pass

class InputError(ApplicationError):
    """Exception raised for errors in the input."""
    def __init__(self, value):
        self.value = value
        self.message = f"InputError: {value} is an invalid input."
        super().__init__(self.message)

class CalculationError(ApplicationError):
    """Exception raised for errors in the calculation."""
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

def perform_calculation(input_value):
    if not isinstance(input_value, int):
        raise InputError(input_value)
    if input_value < 0:
        raise CalculationError("Calculation cannot be performed on negative numbers.")
    return input_value * 2

try:
    result = perform_calculation("abc")
except ApplicationError as e:
    print(e)

In this example:

  • ApplicationError is a base class for other custom exceptions.
  • InputError and CalculationError inherit from ApplicationError.
  • The perform_calculation function raises InputError for invalid input types and CalculationError for invalid calculation conditions.
  • The try block attempts to perform a calculation with an invalid input, and the except block catches the ApplicationError and prints the error message.

Custom Exception Attributes

Custom exceptions can include additional attributes to provide more context about the error.

Example:

class FileReadError(Exception):
    """Exception raised for errors in reading a file."""
    def __init__(self, filename, message="Error reading file"):
        self.filename = filename
        self.message = f"{message}: {filename}"
        super().__init__(self.message)

try:
    raise FileReadError("example.txt")
except FileReadError as e:
    print(f"Filename: {e.filename}")
    print(f"Error message: {e}")

In this example:

  • FileReadError is a custom exception with an additional attribute filename.
  • The raise statement triggers the FileReadError with the specified filename.
  • The except block catches the FileReadError, and the additional attribute filename is accessed and printed along with the error message.

Summary

  • Custom exceptions are defined by creating classes that inherit from Exception or its subclasses.
  • They can include custom initialization and attributes to provide more context about the error.
  • Custom exception hierarchies can be created for more structured error handling.
  • Use raise to trigger custom exceptions and try-except blocks to handle them.

Using custom exceptions can make your code more robust and your error handling more specific and meaningful.

Comments

Popular posts from this blog

TechUplift: Elevating Your Expertise in Every Click

  Unlock the potential of data with SQL Fundamental: Master querying, managing, and manipulating databases effortlessly. Empower your database mastery with PL/SQL: Unleash the full potential of Oracle databases through advanced programming and optimization. Unlock the Potential of Programming for Innovation and Efficiency.  Transform raw data into actionable insights effortlessly. Empower Your Data Strategy with Power Dataware: Unleash the Potential of Data for Strategic Insights and Decision Making.

Relationships between tables

In Power BI, relationships between tables are essential for creating accurate and insightful reports. These relationships define how data from different tables interact with each other when performing analyses or creating visualizations. Here's a detailed overview of how relationships between tables work in Power BI: Types of Relationships: One-to-one (1:1):   This is the most common type of relationship in Power BI. It signifies that one record in a table can have multiple related records in another table. For example, each customer can have multiple orders. Many-to-One (N:1):   This relationship type is essentially the reverse of a one-to-many relationship. Many records in one table can correspond to one record in another table. For instance, multiple orders belong to one customer. One-to-Many (1:N):   Power BI doesn't support direct one-to-many relationships.  One record in table can correspond to many records in another table.  Many-to-Many (N:N):  ...

SQL Fundamentals

SQL, or Structured Query Language, is the go-to language for managing relational databases. It allows users to interact with databases to retrieve, manipulate, and control data efficiently. SQL provides a standardized way to define database structures, perform data operations, and ensure data integrity. From querying data to managing access and transactions, SQL is a fundamental tool for anyone working with databases. 1. Basics of SQL Introduction : SQL (Structured Query Language) is used for managing and manipulating relational databases. SQL Syntax : Basic structure of SQL statements (e.g., SELECT, INSERT, UPDATE, DELETE). Data Types : Different types of data that can be stored (e.g., INTEGER, VARCHAR, DATE). 2. SQL Commands DDL (Data Definition Language) : CREATE TABLE : Define new tables. ALTER TABLE : Modify existing tables. DROP TABLE : Delete tables. DML (Data Manipulation Language) : INSERT : Add new records. UPDATE : Modify existing records. DELETE : Remove records. DQL (Da...