Editor settings

General settings

Save settings

Learn to program with Python

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.

The class 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_number to handle multiple errors without specifying those errors explicitly.

Tests #

  • divide_the_number(4, 2) should return 2.0
  • divide_the_number(10, 4) should return 2.5
  • divide_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 except inside the function
  • Must not use ZeroDivisionError and TypeError directly after except clause
Output will be displayed here