roipoussiere
roipoussiere

Reputation: 5956

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.

Upvotes: 3

Views: 1171

Answers (1)

avenet
avenet

Reputation: 3043

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,

Upvotes: 1

Related Questions