Exception Handling
>>> while True: ... try: ... x = int(raw_input("Please enter a number: ")) ... break ... except ValueError: ... print "Oops! That was no valid number. Try again..." ...
>>> try: ... raise NameError('HiThere') ... except NameError: ... print 'An exception flew by!' ... raise ... An exception flew by! Traceback (most recent call last): File "", line 2, in ? NameError: HiThere
user-defined exceptions
>>> class MyError(Exception): ... def __init__(self, value): ... self.value = value ... def __str__(self): ... return repr(self.value) ...
>>> raise MyError("oops!") Traceback (most recent call last): File "", line 1, in __main__.MyError: 'oops!'
define clean-up action
>>> try: ... raise KeyboardInterrupt ... finally: ... print 'Goodbye, world!' ... Goodbye, world! KeyboardInterrupt