Editor settings

General settings

Save settings

Learn to program with Python

Raising an exception #

You can raise errors explicitly to signal exceptional situations or enforce specific conditions in your code. Raising errors is sometimes called throwing an error.

To raise an error or raise an exception in Python, use the keyword raise, followed by the error object. For example:

raise TypeError("The value is unacceptable")

Here's the output when we run the code above:

### Output
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    raise TypeError("The value is unacceptable")
TypeError: The value is unacceptable

By raising an error instead of simply printing the error message, we can use try-except block to handle the errors when they occur.


Exercise #

  • Update the function divide_the_number to throw errors with custom messages.

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 raise a ZeroDivisionError with the message "You cannot divide by zero!"
  • divide_the_number(10, "Hello") should raise a TypeError with the message "You cannot divide a number with a string!"
Output will be displayed here