In this article, we’ll learn how to tackle bad arguments being passed to functions.
There can be 2 main issues when it comes to arguments,
- The argument is not in the expected range (for example, our function expects an argument in the range of 0 to 10 and we pass in the value 11) and
- The argument is not in the expected type (for example, our function expects integers and we pass in a string)
Let us see how we can deal with these 2 cases of bad inputs. Let us start with
Invalid “Value” of Argument
Let us jump straight into an example. The below program calculates the area of a square.
def square_area(s):
return f"The area of your square is {s * s}"
Have a look at the outputs for the different inputs we enter:
Case 1: Valid Argument
print(square_area(5))
The area of your square is 25
Case 2: Invalid Argument
print(square_area(-10))
The area of your square is 100
The argument in the second case is invalid as no square has a length less than 0 and certainly no square with a negative length will have a positive area.
To tackle this, we can include an if statement to verify if the length is greater than 0 before we get the area:
def square_area(s):
if s > 0:
return f"The area of your square is {s * s}"
else:
raise ValueError("Please enter a number greater than 0")
Now the program will only execute if a valid input is entered, otherwise, it will raise the ValueError appropriately as shown below.
print(square_area(0))
Traceback (most recent call last):
File "/home/main.py", line 7, in <module>
print(square_area(0))
File "/home/main.py", line 5, in square_area
raise ValueError("Please enter a number greater than 0")
ValueError: Please enter a number greater than 0
The raise statement here is used to create and exception and throw it. You can read more about it in the article below.
Python: Manually throw/raise an Exception using the “raise” statement
It is up to the user of our function to deal with this ValueError exception in any way it seems fit. If you wish to learn more about the ValueError exception, we have 2 entire articles dedicated to it which you can find in the links below.
“raise ValueError” What does it mean?
ValueError: A Step By Step Troubleshooting Guide!
Invalid “Type” of Argument
The next type of invalid argument we’ll see is when we simply pass an argument of the wrong type. The appropriate error to be raised in this scenario is TypeError.
Here’s what the structure would look like:
def func(arg):
if <invalid arg type>:
raise TypeError(custom message)
else:
return
For example, here’s a program that returns your birth year depending on the age you enter:
def birth_year(age):
if type(age) == int:
return f"You were born in {2024 - age}"
else:
raise TypeError("Please enter a number")
If we enter the age, we get the answer without any problems:
print(birth_year(20))
Alternatively, an invalid input raises the error:
print(birth_year("20"))
You were born in 2004
Alternatively, an invalid input raises the error:
print(birth_year("Twenty"))
Traceback (most recent call last):
File "/home/main.py", line 7, in <module>
print(birth_year("Twenty"))
File "/home/main.py", line 5, in birth_year
raise TypeError("Please enter a number")
ValueError: Please enter a number
As with the 1st, it is up to the user of our function to deal with this TypeError exception in any way it seems fit. If you wish to learn more about the TypeError exception, we have an entire articles dedicated to it which you can find in the link below.
TypeError: A Step By Step Troubleshooting Guide!
The Fundamentals
Here is a video we made about Exceptions and their place in the programming world. I suggest watching the video if the above explanations made you itchy!
Now that we have a good grasp of the fundamentals, try re-reading the explanations above, I hope it makes much more sense now!
With that being said, let’s wrap it up!
I hope you enjoyed reading this article and found it useful!
Feel free to share it with your friends and colleagues!
If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!
Related Articles
7 Most Common In-Built Exceptions in Python!
Python Raising Error With a Custom Message
Exceptions in Python: Explained for Beginners!
Thanks to Namazi Jamal for his contributions in writing this article!