I get an interesting problem:
Let's take such a function for example:
def SumNumbers(a,b,c,d,e,f):
try:
print("Marta: ",
a," ",b,' ',c,' ',d,' ',e,' ',f,
'=',
a b c d e f)
except TypeError:
print("Enter the values for the 6 parameters of the program")
How we can handling this error in this case:
SumNumbers(1,2,3)
and in this case:
SumNumbers(1,2,3,4,5,5,6,77,7,8,88,8,8,8,8)
Of course, I mean handling this bug in the function body :)
My attempt to intercept a TypeError is unfortunately invalid :(
CodePudding user response:
I think the best thing to do would be to use a decorator, your exception is happening on the function call, not when you try the print. That is why you are not excepting the error as your error happens before your try statement. Here is an example:
def typeErrorException(func):
def inner(*nums):
try:
func(*nums)
except TypeError:
print("Invalid input")
return inner
@typeErrorException
def SumNumbers(a,b,c,d,e,f):
print("Marta: ",
a," ",b,' ',c,' ',d,' ',e,' ',f,
'=',
a b c d e f)
SumNumbers(1,2,3,4,5,6,7)
Your decorator is being called first before your function, trying your function with the given arguments. This means that you don't have to explicitly try, except every time you call the function.
More information on decorators: https://realpython.com/primer-on-python-decorators/
CodePudding user response:
Use *args
:
def SumNumbers(*args):
if len(args) != 6:
print("Enter the values for the 6 parameters of the program")
return
print(f"Marta: {' '.join(str(i) for i in args)} = {sum(args)}")