git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Catch exception with message?


On 04Jun2016 04:44, Piyush Verma <114piyush at gmail.com> wrote:
>Generally we catch exception using
>except Exception as e:
>
>But sometimes, we see same type of exception is present with different
>message.Is there a way to capture same exception with message
>filtering? Please help me to do this.

Quick note: you almost never was to catch "Exception", you almost always want 
to catch a particular Exception subtype such as ValueError.

Regarding your questuon: sure. Just examine the message. For example:

  try:
    ...
  except SomeException as e:
    if e.message == 'some specific string':
      ... handle that ...
    elif e.message.startswith('some prefix'):
      ... handle that ...
    elif ...
      ...
    else:
      # exception _not_ handled, reraise it for someone further out
      # to handle correctly
      raise

Cheers,
Cameron Simpson <cs at zip.com.au>