[Tutor] Trapping Interpreter errors as a string

Remco Gerlich scarblac@pino.selwerd.nl
Wed, 28 Feb 2001 18:07:27 +0100


On Wed, Feb 28, 2001 at 07:58:42AM -0900, Tim Johnson wrote:
> Hi Danny:
> 
> > It sounds like you might want to use exception handling: Exception
> > handling often takes the place of error codes in Python programming.
> I was familar with exeception handling in rebol and C++ when I posted that
> question. What I was looking for was the broadest possible "net", 
> the reason for asking about an error code, was that, if such existed,
> I could modify the error messages.

The broadest possible net is the simple except: clause that catches
everything:

try:
   x = int("whee")
except:
   # Do anything you want here; the current exception is in
   # sys.exc_info().
   import sys
   exception, argument, traceback = sys.exc_info()
   # See also the traceback module for printing info
  
   if exception is ValueError:
       print "Make sure that the string you give to int() has only numbers."
   else:
       # Re-raise every exception you can't handle, like out of memory errors,
       # or KeyboardInterrupt (a user hitting ctrl-C)
       raise