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:
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 aNegativeNumberError
if the input number is negative. - The
try
block attempts to check a negative number, and theexcept
block catches theNegativeNumberError
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:
In this example:
ApplicationError
is a base class for other custom exceptions.InputError
andCalculationError
inherit fromApplicationError
.- The
perform_calculation
function raisesInputError
for invalid input types andCalculationError
for invalid calculation conditions. - The
try
block attempts to perform a calculation with an invalid input, and theexcept
block catches theApplicationError
and prints the error message.
Custom Exception Attributes
Custom exceptions can include additional attributes to provide more context about the error.
Example:
In this example:
FileReadError
is a custom exception with an additional attributefilename
.- The
raise
statement triggers theFileReadError
with the specified filename. - The
except
block catches theFileReadError
, and the additional attributefilename
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 andtry
-except
blocks to handle them.
Using custom exceptions can make your code more robust and your error handling more specific and meaningful.
Comments
Post a Comment