Catch exception with message?

cs at zip.com.au cs at zip.com.au
Fri Jun 3 20:31:23 EDT 2016


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>



More information about the Python-list mailing list