Custom exceptions
You don't have to rely solely on built-in exceptions like IndexError
: you can define custom exceptions that are more specific to your application. You can also define exception hierarchies. All you need to define an exception is a class inherited from the built-in Exception
class or one of its subclasses.
Earlier in the course, you defined an Employee
class and used print
statements and default values to handle errors like creating an employee with a salary below the minimum or giving a raise that is too large. A better way to handle this situation is to use exceptions - because these errors are specific to our application (unlike, for example, a division by zero error, which is universal), it makes sense to use custom exception classes.
This exercise is part of the course
Introduction to Object-Oriented Programming in Python
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define SalaryError inherited from ValueError
____
# Define BonusError inherited from SalaryError
____