Exceptions
Table of Contents
- Overview
- How fast are exceptions?
raise MyException
vsraise MyException()
- Catch multiple exceptions
- Cast exceptions to string
- Built-in Exceptions
- EAFP, LBYL
Overview
else:
must be placed afterexcept:
, which block will be executed if no exception raisedfinally:
will always be executed whether any exception raised or not
How fast are exceptions? discussion
- A
try
/except
block is extremely efficient if no exceptions are raised - Actually catching an exception is expensive.
- Following code only makes sense when you expected the
dict
to have thekey
almost all the time.
raise MyException
vs raise MyException()
discussion
- The short answer is that both
raise MyException
andraise MyException()
do the same thing. - This first form auto instantiates your exception.
- So, use
raise MyException
when there are no arguments.
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
- Normally,
KeyboardInterrupt
is raised by the python defineddefault_int_handler
forSIGINT
(code) - However, if signal mask contains
SIG_IGN
, it won't, which means, There would be noKeyboardInterrupt
. - Most shell like
bash
set the signal mask ofSIG_IGN
toSIGINT
andSIGQUIT
when it runs the process background (like$ cmd &
)
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.