Custom exceptions
You don't have to rely solely on built-in exceptions like IndexError
: you can define your own exceptions 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.
In Chapter 1, 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 big. 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
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
____