简体   繁体   English

无效的参数引发异常

[英]Invalid argument raise exception

How do I test my parameter if it will raise an exception without actually raising it, using try and except ? 我如何使用tryexcept测试我的参数是否会引发异常而不实际引发异常?

class MyClass:
    def function(parameter):
        pass

parameter is an ambiguous function that may raise 1 or more of any exception, for example: parameter是一个模糊函数,可能引发任何异常中的1个或多个,例如:

parameter = pow("5", 5)

A TypeError is raised as soon as the function is called and before the function can execute its statements. 在调用函数后且函数可以执行其语句之前,将TypeError

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. 现在,您可以检查errors并找出引发了哪些异常。

If you expect the parameter to be a certain type, you can use type(paramter) is parametertype . 如果您希望参数为某种类型,则可以使用type(paramter) is parametertype

For example, if you wanted to verify that 'i' is an int, run instructions if(type(i) is int): 例如,如果您想验证“ i”是否为整数,请运行指令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? 也许您的意思是如何捕获由无效函数调用引起的TypeError异常?

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. 您不会在函数中捕获它们,当然也不会在def foo(bar):行中捕获它们。

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." 在对另一个答案的评论中,您说: parameter是另一个函数;例如: parameter = pow("5", 5)会引发TypeError ,但它可以是任何类型的函数和任何类型的异常。”

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: 如果要在函数内部捕获异常,则必须在该函数内部调用paramenter(我认为这是可以调用的):

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. 如果您确实需要在函数内部调用“ paramenter”。 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. 在此示例中,引发异常是pow not function ,因此,好的做法是将两个不同的调用分开,并用try-except语句包装可能失败的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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