You can raise an exception in your Python code using the raise keyword.
There are many predefined exceptions in Python. You can also create your own exceptions, typically by creating a subclass of the builtin Exception class.
Here’s a program that calculates an area. If you pass negative values to the calculate_area function, it raises a ValueError exception. This type of exception is typically used when a function receives arguments of the right type but the wrong value.
def calculate_area(length, width):
if length < 0:
raise ValueError("Length parameter cannot be negative.")
if width < 0:
raise ValueError("Width parameter cannot be negative.")
return length * width
def main():
area = calculate_area(5, -1)
print(f"The area is {area} square metres")
main()
Traceback (most recent call last):
File "/Users/john/Documents/Python WordPress/./strings.py", line 15, in <module>
main()
File "/Users/john/Documents/Python WordPress/./strings.py", line 12, in main
area = calculate_area(5, -1)
File "/Users/john/Documents/Python WordPress/./strings.py", line 7, in calculate_area
raise ValueError("Width parameter cannot be negative.")
ValueError: Width parameter cannot be negative.
Leave a Reply