简体   繁体   English

从警告链接异常时发生TypeError

[英]TypeError when chaining exception from a warning

I am trying to catch a warning that is raised as an error by applying the 'error' filter of warnings.simplefilter . 我正在尝试通过应用warnings.simplefilter'error'过滤器来捕获作为错误提出的warnings.simplefilter A minimum working example is given below: 下面给出一个最小的工作示例:

>>> import warnings
>>> warnings.simplefilter('error')
>>> try:
...     warnings.warn('test')
... except UserWarning:
...     raise ValueError
...
ValueError: 

This works fine, but if I want to chain this so that the traceback from the warning is included, I get the following TypeError : 这可以很好地工作,但是如果我要链接它以便包括警告的回溯,我将得到以下TypeError

>>> import sys
>>> try:
...     warnings.warn('test')
... except UserWarning:
...     raise ValueError from sys.exc_info()[2]
...
TypeError: exception causes must derive from BaseException

It seems that even though I am raising a class derived from BaseException (ie the ValueError ), the information from the traceback from the UserWarning seems to be tricking Python into thinking I am still raising the UserWarning . 看来,即使我正在提出一个从BaseException派生的类(即ValueError ),来自UserWarning似乎在欺骗Python使其认为我仍在提出UserWarning

Is this the expected behavior? 这是预期的行为吗? If so, is there a good workaround? 如果是这样,是否有一个好的解决方法?

I am on Python 3.4.3. 我使用的是Python 3.4.3。

You are trying to use the traceback object as the exception: 您正在尝试使用traceback对象作为例外:

raise ValueError from sys.exc_info()[2]

sys.exc_info() returns a tuple of (ExceptionType, exception_instance, traceback) ; sys.exc_info()返回(ExceptionType, exception_instance, traceback)的元组; you'd want index 1 here (remember Python counts indices from 0 !): 您需要在此处创建索引1(请记住Python从0计数索引!):

raise ValueError from sys.exc_info()[1]

Much better, capture the exception instance in a variable directly: 更好的是,直接在变量中捕获异常实例:

try:
    warnings.warn('test')
except UserWarning as warning:
    raise ValueError from warning

That way you don't have to count out tuple indices. 这样,您就不必算出元组索引。

When you set the warnings filter to 'error' , the exceptions are subclasses of the Warning exception class , which inherits from Exception , see the Exception Hierachy section . 将警告过滤器设置为'error' ,异常是Warning异常类的子类, 该类继承自Exception ,请参见“ 异常层次”部分

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

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