[英]Can't catch my raise exception python
I call an external program and raise an error when it fails. 我调用外部程序并在失败时引发错误。 The problem is I can't catch my custom exception. 问题是我无法捕捉到我的自定义异常。
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'
In this case, python prints Oops, something went wrong: [the sderr message] with a stack-trace. 在这种情况下,python打印Oops,出了点问题:[带有堆栈跟踪的sderr消息] 。
Try this: 尝试这个:
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
Take a look at the type of the exception type (denoted by type(e)) value. 查看异常类型的类型(由类型(e)表示)值。 Looks like it's an exception you will need to catch... 看起来这是一个例外,你需要抓住......
Hope it helps, 希望能帮助到你,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.