-
1. Introduction to Python
-
2. Python Basics
-
3. Working with Data Structures
-
4. Functions and Modules
-
5. Object-Oriented Programming (OOP)
-
6. File Handling
-
7. Error and Exception Handling
-
8. Python for Data Analysis
-
9. Advanced Topics in Python
-
10. Working with APIs
-
11. Python for Automation
-
12. Capstone Projects
- 13. Final Assessment and Quizzes
7.3.1 Custom exceptions using raise
In Python, you can create your own custom exceptions to handle specific error scenarios in your program. Custom exceptions are especially useful when the built-in exceptions do not cover the exact nature of the error. You can use the raise keyword to trigger these custom exceptions when needed.
1. Why Create Custom Exceptions?
Custom exceptions are helpful when:
- You need to differentiate between various types of errors specific to your program or domain.
- You want to add additional information to the exception, such as custom error messages or data.
- You need to raise exceptions in a more structured way to manage errors effectively.
By using custom exceptions, you improve the readability, maintainability, and clarity of error handling in your programs.
2. Creating a Custom Exception Class
A custom exception is created by defining a class that inherits from Python's built-in Exception class or one of its subclasses. You can then customize the class with additional behavior, such as providing custom error messages.
Basic Syntax:
class CustomException(Exception): def __init__(self, message="Default error message"): self.message = message super().__init__(self.message)
- Explanation:
- The class CustomException inherits from the Exception class.
- The __init__() method is used to initialize the exception with a custom message.
- The super().__init__(self.message) calls the parent Exception class's constructor, passing the message to it.
3. Raising Custom Exceptions
Once you've created a custom exception, you can raise it in your program using the raise keyword, typically when some condition is met that requires error handling.
Example: Raising a Custom Exception
class NegativeAgeError(Exception): def __init__(self, message="Age cannot be negative"): self.message = message super().__init__(self.message) def set_age(age): if age < 0: raise NegativeAgeError("Provided age is negative") return age try: set_age(-5) except NegativeAgeError as e: print(f"Error: {e}")
- Explanation:
- The NegativeAgeError exception is raised when a negative age is provided to the set_age function.
- The raise statement triggers the exception, which is then caught in the try-except block.
- The custom message "Provided age is negative" is passed and displayed as part of the exception.
4. Custom Exception with Additional Data
You can also include additional data or attributes in your custom exception to provide more context about the error. This can be helpful for debugging or logging purposes.
Example: Custom Exception with Extra Data
class InvalidInputError(Exception): def __init__(self, message="Invalid input provided", input_value=None): self.message = message self.input_value = input_value super().__init__(self.message) def process_input(value): if not isinstance(value, int): raise InvalidInputError(f"Expected an integer, but got {type(value)}", input_value=value) return value * 2 try: process_input("string") except InvalidInputError as e: print(f"Error: {e}") print(f"Invalid input was: {e.input_value}")
- Explanation:
- The InvalidInputError custom exception includes an additional attribute input_value, which stores the invalid input value.
- If the input is not an integer, the exception is raised with a custom message that includes the type of the invalid input.
- The input_value is accessible from the exception object (e.input_value), which can be useful for debugging or logging.
5. Catching and Handling Custom Exceptions
Once a custom exception is raised, it can be caught in a try-except block. The exception is then handled according to the program’s needs (e.g., logging the error, alerting the user, etc.).
Example: Handling Custom Exception
class DivByZeroError(Exception): def __init__(self, message="Cannot divide by zero"): self.message = message super().__init__(self.message) def divide(a, b): if b == 0: raise DivByZeroError("Attempted to divide by zero!") return a / b try: result = divide(10, 0) except DivByZeroError as e: print(f"Error: {e}")
- Explanation: The custom exception DivByZeroError is raised when there is an attempt to divide by zero. The exception is caught and handled in the try-except block, and the error message is printed.
6. Best Practices for Creating Custom Exceptions
- Be Specific: Name your custom exceptions according to the problem they are solving (e.g., FileNotFoundError, InvalidUserInputError).
- Inherit from Exception: Always inherit from Python’s built-in Exception class or one of its subclasses to maintain compatibility with the standard exception handling system.
- Provide Meaningful Error Messages: Include useful information in your error messages, such as the reason for the exception and any relevant data, to make debugging easier.
- Avoid Overuse: Use custom exceptions only when the built-in exceptions don't cover the specific error scenario. Overusing custom exceptions can make your code more complex than it needs to be.
7. Example: Full Program with Custom Exception
class WithdrawalLimitError(Exception): def __init__(self, message="Withdrawal limit exceeded"): self.message = message super().__init__(self.message) class BankAccount: def __init__(self, balance=0): self.balance = balance self.withdrawal_limit = 1000 def withdraw(self, amount): if amount > self.withdrawal_limit: raise WithdrawalLimitError(f"Requested withdrawal of {amount} exceeds limit of {self.withdrawal_limit}") if amount > self.balance: raise ValueError("Insufficient funds") self.balance -= amount return self.balance # Example usage account = BankAccount(5000) try: account.withdraw(1500) # Exceeds withdrawal limit except WithdrawalLimitError as e: print(f"Error: {e}") except ValueError as e: print(f"Error: {e}")
- Explanation:
- The WithdrawalLimitError custom exception is raised if a user tries to withdraw more than the set withdrawal limit.
- The withdraw method in the BankAccount class checks whether the requested amount exceeds the limit and raises the appropriate exception.
- The exception is caught in the try-except block, and the error message is printed.
Conclusion
Using the raise keyword, you can create and raise custom exceptions to handle specific error conditions in your Python programs. This approach enhances error handling, making your code more robust, informative, and maintainable. By defining custom exceptions, you can ensure that your application can deal with errors in a way that is meaningful to the domain and easier to debug.
Commenting is not enabled on this course.