9

I have a script that catches all exceptions, which works great unless I want to abort the script manually (with control + c). In this case the abort command appears to be caught by the exception instead of quitting.

Is there a way to exclude this type of error from the exception? For example something as follows:

try:
    do_thing()
except UserAbort:
    break
except Exception as e:
    print(e)
    continue
Drise
  • 4,164
  • 5
  • 38
  • 64
Alex
  • 10,175
  • 6
  • 60
  • 68

1 Answers1

8

You could just force to exit the program whenever the exception happens:

import sys
# ...
try:
    do_thing()
except UserAbort:
    break
except KeyboardInterrupt:
    sys.exit()
    pass
except Exception as e:
    print(e)
    continue
Adriano Martins
  • 1,762
  • 1
  • 23
  • 21
  • Wait, but the OP _wants_ ctrl + c to crash the program, right? "which works great unless I want to abort the script manually (with control + c)" – roganjosh Mar 19 '18 at 21:50
  • Yes @roganjosh I am trying to crash the program. I believe you are correct that catching a general `Exception` will not include `KeyboardInterrupt` – Alex Mar 19 '18 at 21:52
  • @AlexG [It won't catch it](https://stackoverflow.com/a/18982771/4799172) – roganjosh Mar 19 '18 at 21:55
  • Sorry about that, I've misread the question. A simply re-raise should fix though – Adriano Martins Mar 19 '18 at 22:08