Overriding a built-in exception handler

C

callmebill

I'm having a tough time figuring this one out:


class MyKBInterrupt( ..... ):
print "Are you sure you want to do that?"

if __name__ == "__main__":
while 1:
print "Still here..."


So this thing keeps printing "Still here..." until the user hits ctl-c,
at which time the exception is passed to MyKBInterrupt to handle the
exception, rather than to whatever the built-in handler would be.

I've Read-TFM, but I only see good info on how to create my own class
of exception; I don't see anything on how to override an existing
exception handler.

Thanks in advance for any help.
 
J

Jaime Wyant

You can't override an exception. You can only catch whatever
exception is thrown.

For your case, you would want to wrap that while loop up in a
try/catch block like this:

try:
while 1:
print "Yay for me!"
except KeyboardInterrupt:
print "CTRL-C caught"

Someone had mentioned possibly overriding sys.excepthook, but that
doesn't really "override" an exception handler. That function is
called when an unhandled exception occurs. That little hook is really
nice if you want to display information back to the user and possibly
report the info back to a server somewhere.

jw
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top