-2

I am having trouble dealing with exceptions where the incorrect number of arguments are given when a function is called.

Here's a simplified example:

def func(arg1, arg2):
    return arg1 + arg2

func(46)

When the function is called without the correct number of arguments, the following error message is generated:

TypeError: func() missing 1 required positional argument: 'arg2'

I have tried to add a try, except to handle this exception, as follows, but it does not work:

def func(arg1, arg2):
    try:
        return arg1 + arg2
    except:
        return 'Incorrect input'

The function still generates the error message, rather than the 'Incorrect input' statement.

How can I have the function return the message 'Incorrect input' when the wrong number of arguments are given when the function is called?

Thanks

I'mahdi
  • 11,310
  • 3
  • 17
  • 23
ancient
  • 15
  • 6
  • Why would you want that? The developer should be able to understand the given error message just fine. – luk2302 Sep 04 '21 at 07:44

2 Answers2

0

The exception happens upon the function call, before entering func so you did not manage to catch it:

def func(arg1, arg2):
        return arg1 + arg2

try:
    func(46)
except TypeError:
    print('Incorrect input')

Note the error message you received state it is 'TypeError' so you should catch only this kind of error.

Nir
  • 96
  • 1
  • 7
0

you can create your own try-except like below:

class IncorrectInput(Exception):
    def __init__(self, msg):
        self.msg = msg
    def __str__(self):
        return repr(self.msg)

def func(arg1, arg2 = 0):
    try:
        if type(arg1)!= int or type(arg2)!= int:
            raise IncorrectInput("Incorrect input")
        return arg1 + arg2 
    except IncorrectInput as e:
        print(e)
    
    
func('a', 'b')

output:

'Incorrect input'

if you can use if-else instead of try-except. you can try this:

def func(arg1, arg2 = 0):
    if isinstance(arg1, int) and isinstance(arg1, int):
        return arg1 + arg2
    else:
        return 'Incorrect input'
I'mahdi
  • 11,310
  • 3
  • 17
  • 23