Home > Back-end >  Python 3 Try Except Error Handling With Missing Arguments in Function
Python 3 Try Except Error Handling With Missing Arguments in Function

Time:09-18

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

CodePudding user response:

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.

CodePudding user response:

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'
  • Related