4

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

2 Answers 2

4

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...'
Sign up to request clarification or add additional context in comments.

7 Comments

So if I want to handle any exception's text, but I don't know every exception's name, how do I do this?
@JoeDoe see the code above, 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?
@JoeDoe you don't, as that's not explicit (which exceptions will you handle? What do you expect your code to raise? Etc.). Explicit is better than implicit. In general, however, if you catch BaseException, all other exceptions should be caught also.
I want to the code would handle any exception. Because I didn't know about KeyboardInterrupt, handled only Exception and then that error showed up. So I want to handle any exception as e and print(str(e))
@JoeDoe catching every exception is not a very good idea, you won't be able to interrupt your program with Ctrl/C for one.
|
0

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))

3 Comments

So if I want to handle any exception's text, but I don't know every exception's name, how do I do this?
You would do 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.
In case except I can't get the text of exception. I'll try BaseException, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.