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_numberto throw errors with custom messages.
Tests #
divide_the_number(4, 2)should return2.0divide_the_number(10, 4)should return2.5divide_the_number(10, 0)should raise aZeroDivisionErrorwith the message"You cannot divide by zero!"divide_the_number(10, "Hello")should raise aTypeErrorwith the message"You cannot divide a number with a string!"
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