0

I want to pause a python script when Crtl+C is pressed but to handle the rest of exceptions with different code.

If I got:

except KeyboardInterrupt:
    print '\nPausing...  (Hit ENTER to continue, type quit to exit.)'
    try:
        response = raw_input()
        if response == 'quit':
            break
        print 'Resuming...'
    except KeyboardInterrupt:
        print 'Resuming...'
        continue        

except Exception, e:
    print traceback.print_exc()
    continue
    sleep(170)

Won't second except go also for KeyboardInterrupt, isn't a keyboard interrupt supposed to be an exception?

1 Answer 1

1

Won't second except go also for KeyboardInterrupt, isn't a keyboard interrupt supposed to be an exception?

Well, this is interesting... Apparently it is not a subclass of the Exception class, but is child to a superclass called BaseException.

Python's doc Built-in Exceptions explains why they implemented it this way:

The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting.

And it can be checked like this:

>>> issubclass(KeyboardInterrupt, Exception)
False
>>> issubclass(KeyboardInterrupt, BaseException)
True
>>> issubclass(Exception, BaseException)
True

Nevertheless, even if you changed your last except block to catch a BaseException instead of a Exception, it would still not enter it (because your inner except KeyboardInterrupt avoids the exception to be thrown to the outer indentation or "parent" levels).

In case you also removed this inner except KeyboardInterrupt block, the exception would be thrown to the outer indentation, which I assume it does not exist (given your indentation level) and the execution would terminate...

Sign up to request clarification or add additional context in comments.

Comments

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.