Table of Contents
- How fast are exceptions?
- Catch multiple exceptions
- Cast exceptions to string
- Built-in Exceptions
- EAFP, LBYL
else:must be placed after
except:, which block will be executed if no exception raised
finally:will always be executed whether any exception raised or not
How fast are exceptions? discussion
exceptblock is extremely efficient if no exceptions are raised
- Actually catching an exception is expensive.
- Following code only makes sense when you expected the
dictto have the
keyalmost all the time.
raise MyException vs
raise MyException() discussion
- The short answer is that both
raise MyException()do the same thing.
- This first form auto instantiates your exception.
- So, use
raise MyExceptionwhen there are no arguments.
Catch multiple exceptions howto
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
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.
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
KeyboardInterruptis raised by the python defined
- However, if signal mask contains
SIG_IGN, it won't, which means, There would be no
- Most shell like
bashset the signal mask of
SIGQUITwhen it runs the process background (like
$ cmd &)
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.