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

Performance Optimization

Performance optimization in SQL is crucial for ensuring that your database queries run efficiently, especially as the size and complexity of your data grow. Here are several strategies and techniques to optimize SQL performance: Indexing Create Indexes : Primary Key and Unique Indexes : These are automatically indexed. Ensure that your tables have primary keys and unique constraints where applicable. Foreign Keys : Index foreign key columns to speed up join operations. Composite Indexes : Use these when queries filter on multiple columns. The order of columns in the index should match the order in the query conditions. Avoid Over-Indexing:  Too many indexes can slow down write operations (INSERT, UPDATE, DELETE). Only index columns that are frequently used in WHERE clauses, JOIN conditions, and as sorting keys. Query Optimization Use SELECT Statements Efficiently : SELECT Only Necessary Columns : Avoid using SELECT * ; specify only ...

DAX UPPER Function

The DAX UPPER function in Power BI is used to convert all characters in a text string to uppercase. This function is useful for standardizing text data, ensuring consistency in text values, and performing case-insensitive comparisons. Syntax: UPPER(<text>) <text>: The text string that you want to convert to uppercase. Purpose: The UPPER function helps ensure that text data is consistently formatted in uppercase. This can be essential for tasks like data cleaning, preparing text for comparisons, and ensuring uniformity in text-based fields. E xample: Suppose you have a table named "Customers" with a column "Name" that contains names in mixed case. You want to create a new column that shows all names in uppercase. UppercaseName = UPPER(Customers[Name]) Example Scenario: Assume you have the following "Customers" table: You can use the UPPER function as follows: Using the UPPER function, you can convert all names to uppercase: UppercaseName = ...

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.