-1

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
  • 23,382
  • 5
  • 22
  • 30
ancient
  • 25
  • 7
  • 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

1 Answers1

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
  • 106
  • 1
  • 7