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:
In this example:
NegativeNumberErroris a custom exception that includes an__init__method to store the invalid value and a custom error message.- The
check_positivefunction raises aNegativeNumberErrorif the input number is negative. - The
tryblock attempts to check a negative number, and theexceptblock catches theNegativeNumberErrorand 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:
In this example:
ApplicationErroris a base class for other custom exceptions.InputErrorandCalculationErrorinherit fromApplicationError.- The
perform_calculationfunction raisesInputErrorfor invalid input types andCalculationErrorfor invalid calculation conditions. - The
tryblock attempts to perform a calculation with an invalid input, and theexceptblock catches theApplicationErrorand prints the error message.
Custom Exception Attributes
Custom exceptions can include additional attributes to provide more context about the error.
Example:
In this example:
FileReadErroris a custom exception with an additional attributefilename.- The
raisestatement triggers theFileReadErrorwith the specified filename. - The
exceptblock catches theFileReadError, and the additional attributefilenameis accessed and printed along with the error message.
Summary
- Custom exceptions are defined by creating classes that inherit from
Exceptionor 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
raiseto trigger custom exceptions andtry-exceptblocks to handle them.
Using custom exceptions can make your code more robust and your error handling more specific and meaningful.
Comments
Post a Comment