简体   繁体   中英

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.

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. Looks like it's an exception you will need to catch...

Hope it helps,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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