Exceptions

Table of Contents

Overview

How fast are exceptions? discussion

try:
    value = mydict[key]
except KeyError:
    mydict[key] = getvalue(key)
    value = mydict[key]

raise MyException vs raise MyException() discussion

Catch multiple exceptions howto

Because except TypeError,e is equivalent to exception TypeError as e, you must use tuple to catch multiple exceptions like except (TypeError, ValueError) as e

Cast exceptions to string howto

If str() or unicode() is called on an instance of this class(BaseException), the representation of the argument(s) to the instance are returned, or the empty string when there were no arguments.

BaseException.args: The tuple of arguments given to the exception constructor.

Built-in Exceptions

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
      |    +-- BufferError
      |    +-- ArithmeticError
      |    |    +-- FloatingPointError
      |    |    +-- OverflowError
      |    |    +-- ZeroDivisionError
      |    +-- AssertionError
      |    +-- AttributeError
      |    +-- EnvironmentError
      |    |    +-- IOError
      |    |    +-- OSError
      |    |         +-- WindowsError (Windows)
      |    |         +-- VMSError (VMS)
      |    +-- EOFError
      |    +-- ImportError
      |    +-- LookupError
      |    |    +-- IndexError
      |    |    +-- KeyError
      |    +-- MemoryError
      |    +-- NameError
      |    |    +-- UnboundLocalError
      |    +-- ReferenceError
      |    +-- RuntimeError
      |    |    +-- NotImplementedError
      |    +-- SyntaxError
      |    |    +-- IndentationError
      |    |         +-- TabError
      |    +-- SystemError
      |    +-- TypeError
      |    +-- ValueError
      |         +-- UnicodeError
      |              +-- UnicodeDecodeError
      |              +-- UnicodeEncodeError
      |              +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
     +-- ImportWarning
     +-- UnicodeWarning
     +-- BytesWarning

KeyboardInterrupt

SystemExit

raise SystemExit()       # exit status: 0
raise SystemExit(99)     # exit status: 99
raise SystemExit('foo')  # print 'foo', exit status: 1

EAFP, LBYL

# EAFP (Easier to ask for forgiveness than permission)
try:
    return mapping[key]
except KeyError:
    pass


# LBYL (Look Before you leap)
if key in mapping:
    return mapping[key]

LBYL can fail if another thread removes the key after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach.