2

I am communicating with an API that raises an exception like this: raise Exception("end of time").

How do I catch Exception only when the string argument is "end of time"?

I don't want to do:

except Exception:
    pass

I want to do something like:

except Exception("end of time"):
    pass

However, this does not catch the exception.

Example traceback:

File "test.py", line 250, in timeout_handler
    raise Exception("end of time")
Exception: end of time

2 Answers2

4

Use the Exception .args to filter things if you need to do so:

try:
    raise Exception("end of time")
except Exception as e:
    if e.args[0] == 'end of time':
        pass # handle
    else:
        raise
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
0

Well, the ideal case should have been raising a custom exception. Since that's not the case a workaround can be checking the exception message.

except Exception as exp:
    if str(exp) == 'end of time':
        # do something
    else:
        # pass or do something else
hspandher
  • 15,934
  • 2
  • 32
  • 45