无法捕获我的引发异常python

时间:2015-09-29 13:03:24

标签: 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=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打印糟糕,出现问题:[带有堆栈跟踪的sderr消息]

1 个答案:

答案 0 :(得分:1)

试试这个:

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)表示)值。看起来它是一个例外,你需要抓住......

希望它有所帮助,