简体   繁体   中英

Invalid argument raise exception

How do I test my parameter if it will raise an exception without actually raising it, using try and except ?

class MyClass:
    def function(parameter):
        pass

parameter is an ambiguous function that may raise 1 or more of any exception, for example:

parameter = pow("5", 5)

A TypeError is raised as soon as the function is called and before the function can execute its statements.

From what I can understand, you want to handle the exceptions raised and also inspect what sort of errors were raised for further inspection? Here is one way of doing it.

class Foo(object):
    def find_errors(arg):
        errors = []
        try:
            # do something
        except TypeError as e:
            errors.append(e)
            # handle exception somehow
        except ValueError as e:
            errors.append(e)
            # handle exception somehow
        # and so on ...
        finally:
            pass #something here

        return errors, ans

Now you can inspect errors and find out what exceptions have been raised.

If you expect the parameter to be a certain type, you can use type(paramter) is parametertype .

For example, if you wanted to verify that 'i' is an int, run instructions if(type(i) is int):

By edit:

try:
    pow("5",5)
    return 0
except Exception, err:
    sys.stderr.write('ERROR: %s\n' % str(err))
    return 1

Perhaps what you mean is how to catch the TypeError exceptions caused by invalid function calls?

Like this:

def foo(bar):
    pass

foo(1, 2)

You don't catch them in the function and certainly not in the def foo(bar): line.

It's the caller of the function that made an error so that's where you catch the exception:

try:
    foo(1, 2)
except TypeError:
    print('call failed')

In a comment to another answer you said: " parameter is another function; take for example: parameter = pow("5", 5) which raises a TypeError , but it could be any type of function and any type of exception."

If you want to catch the exeption inside your function you have to call the paramenter (which I'm assuming is callable) inside that function:

def function(callable, args=()):
    try:
        callable(*args)
    except:
        print('Ops!')

Example:

>>> function(pow, args=("5", 5))
Ops!

This is if you really need to call your "paramenter" inside the function. Otherwise your should manage its behaviour outside, maybe with something like:

>>> try:
...     param = pow('5', 5)
... except:
...     param = 10
... 
>>> param
10
>>> function(param)

In this example, to raise an exception is pow not function , so it's a good practice to separate the the two different call, and wrap with a try-except statement the code that might fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM