Python Can';我没听懂我的话
我调用一个外部程序,当它失败时引发一个错误。问题是我无法捕获自定义异常Python Can';我没听懂我的话,python,exception,raise,Python,Exception,Raise,我调用一个外部程序,当它失败时引发一个错误。问题是我无法捕获自定义异常 from subprocess import Popen, PIPE class MyCustomError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) def call(): p = Popen(some_command, stdout=P
from subprocess import Popen, PIPE
class MyCustomError(Exception):
def __init__(self, value): self.value = value
def __str__(self): return repr(self.value)
def call():
p = Popen(some_command, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stderr is not '':
raise MyCustomError('Oops, something went wrong: ' + stderr)
try:
call()
except MyCustomError:
print 'This message is never displayed'
在本例中,python打印Oops时,出现了错误:[sderr消息]和堆栈跟踪。尝试以下操作:
from subprocess import Popen, PIPE
class MyCustomError(Exception):
def __init__(self, value): self.value = value
def __str__(self): return repr(self.value)
def call():
p = Popen(['ls', '-la'], stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if self.stderr is not '':
raise MyCustomError('Oops, something went wrong: ' + stderr)
try:
call()
except MyCustomError:
print 'This message is never displayed'
except Exception, e:
print 'This message should display when your custom error does not happen'
print 'Exception details', type(e), e.message
看看异常类型(由类型(e)表示)值的类型。看起来这是一个例外,你需要抓住
希望对我有所帮助,代码的工作方式与您期望的一样。我注意到,
if
行中没有定义self
。此外,在子类化时,通常还需要调用父类的\uuuu init\uuuu
。您需要提供一个。您应该捕获异常,代码中没有错误,请添加stacktrace。问题是发生了另一个您无法捕获的异常。旁注:如果stderr不是“”,请不要执行:
;这依赖于一个巧合的对象身份测试,但是没有保证。由于您知道它是一个str
,而空的str
是falsy(以及所有其他的truthy),您可以使用if stderr:
更简单/有效地测试它。例如,如果移动到Python3,默认情况下,communicate
返回的是bytes
,而不是str
b'
将是一个无错误的完成,如果stderr:,它将在中正常运行,但如果stderr不是“”:
,则不会在中正常运行。
。另请注意:您的自定义错误正在执行异常
将为您执行的操作(您只需给传递了错误名称的参数)。只需使用类MyCustomError(Exception):通过
,它就可以正常工作(并且可以通过使用通用变量名与其他异常
s进行正确的互操作);不需要冗余的\uuuu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。