As 3
As 3
EXCEPTION HANDLING
Exercise
Catching exceptions
Before you start writing your own custom exceptions, let's make sure you have the
fundamentals of handling exceptions down.
In this exercise, you are given a function invert_at_index(x, ind) that takes two
arguments,
a list x and an index ind, and inverts the element of the list at that index.
For example invert_at_index([5,6,7], 0) returns 1/5, or 0.2 .
Your goal is to implement error-handling to raise custom exceptions based on the
type of error that occurs.
----Instructions----
Use a try - except - except pattern (with two except blocks) inside the function to
catch and handle two exceptions as follows:
0.16666666666666666
Cannot divide by zero!
None
Index out of range!
None
CODE
# Modify the function to catch exceptions
def invert_at_index(x, ind):
____:
return 1/x[ind]
_____:
print("____")
____:
print("____")
a_list = [5,6,0,7]
# Works okay
print(invert_at_index(a_list, 1))
# Potential ZeroDivisionError
print(invert_at_index(a_list, 2))
# Potential IndexError
print(invert_at_index(a_list, 5))
To check
Exercise
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.
Instructions 1/3
1a. Define an empty class SalaryError inherited from the built-in ValueError class.
1b. Define an empty class BonusError inherited from the SalaryError class.
Instructions 2/3
-----CODE-----
class Employee:
MIN_SALARY = 30000
MAX_RAISE = 5000
self.salary = salary
Instructions 3/3
Implement exceptions in the give_bonus() method:
raising a BonusError if the bonus amount is larger than the class' MAX_BONUS,
and raising a SalaryError if the result of adding the bonus would be lower than the
class' MIN_SALARY.
CODE-3
class SalaryError(ValueError):
pass
class BonusError(SalaryError):
pass
class Employee:
MIN_SALARY = 30000
MAX_BONUS = 5000
# Raise exceptions
def give_bonus(self, amount):
if amount > Employee.MAX_BONUS:
____("The bonus amount is too high!")
elif self.salary + amount < Employee.MIN_SALARY:
____("The salary after bonus is too low!")
self.salary += amount