Here's the code:
try:
input() # I hit Ctrl+C
except Exception as e:
print(str(e))
Here's the traceback:
Traceback (most recent call last):
File "C:\Users\User\Desktop\test.py", line 2, in <module>
input()
KeyboardInterrupt
please, be explicit, when you want to catch KeyboardInterrupt:
try:
input() # I hit Ctrl+C
except Exception as e:
print(str(e))
except KeyboardInterrupt :
print 'ok, ok, terminating now...'
except KeyboardInterrupt catches Ctrl/C, and you may handle all other exceptions in the next except statement. Or do you want to do something completely different?BaseException, all other exceptions should be caught also.as e and print(str(e))Ctrl/C for one.KeyboardInterrupt is not an Exception but only a BaseException, so your except is not handling it:
>>> issubclass(KeyboardInterrupt, Exception)
False
>>> issubclass(KeyboardInterrupt, BaseException)
True
Handling a BaseException gives you access to any exception, but is discouraged:
try:
# ...
except BaseException as e:
print(str(e))
except BaseException: or just except:, but both is discouraged as, among other things - like in your example - you can no longer interrupt your program. It is better to be as explicit as possible and if needed add more exception types you want handled.except I can't get the text of exception. I'll try BaseException, thanks