11

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,310
  • 5
  • 41
  • 66
Alex
  • 12,078
  • 6
  • 64
  • 74

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,788
  • 1
  • 19
  • 23
  • 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
  • 1
    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
  • 1
    @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
  • I would be more comfortable doing `except KeyboardInterrupt as e` then using `raise e` instead just in case some module higher up in the call chain catches it... – A Kareem Dec 24 '22 at 09:37