Inheritance and except clause #
Now we know that an error is just an object created by an error class that inherits from Python's built-in class Exception. When using inheritance in the except clause, catching a base class can also catch its subclasses, for example:
class FirstError(Exception):
pass
try:
raise FirstError("An error message")
except Exception as e:
print("The error is caught")
# Output
The error is caught
In the example above, the try-except block catches the error FirstError, even though it is not specified after except.
Exception also inherits from BaseException, but we rarely use it after except clause. This is because some actions, such as exiting the program or using the keyboard to stop the program causes an errors that inherits from BaseException class. If we were to use BaseException class after except clause, we won't be able to stop or exit the program from those actions.
Exercise #
- Update the function
divide_the_numberto handle multiple errors without specifying those errors explicitly.
Tests #
divide_the_number(4, 2)should return2.0divide_the_number(10, 4)should return2.5divide_the_number(10, 0)should print the message"You cannot divide by zero!"divide_the_number(10, "Hello")should print the message"You cannot divide a number with a string!"- Must use only one
exceptinside the function - Must not use
ZeroDivisionErrorandTypeErrordirectly afterexceptclause
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules