try...except...else...finally

Python can throw - pardon, raise - Exceptions:

  1. >>> try:
  2. ... a = 1 / 0
  3. ... except Exception as e:
  4. ... print 'oops: %s' % e
  5. ... else:
  6. ... print 'no problem here'
  7. ... finally:
  8. ... print 'done'
  9. ...
  10. oops: integer division or modulo by zero
  11. done

If the exception is raised, it is caught by the except clause, which is executed, while the else clause is not. If no exception is raised, the except clause is not executed, but the else one is. The finally clause is always executed.

There can be multiple except clauses for different possible exceptions:

  1. >>> try:
  2. ... raise TypeError()
  3. ... except ValueError:
  4. ... print 'value error'
  5. ... except Exception:
  6. ... print 'generic error'
  7. ...
  8. generic error

The else and finally clauses are optional.

Here is a list of built-in Python exceptions + HTTP (defined by web2py)

  1. BaseException
  2. +-- SystemExit
  3. +-- KeyboardInterrupt
  4. +-- GeneratorExit
  5. +-- Exception
  6. +-- HTTP (defined by web2py)
  7. +-- StopIteration
  8. +-- StandardError
  9. | +-- BufferError
  10. | +-- ArithmeticError
  11. | | +-- FloatingPointError
  12. | | +-- OverflowError
  13. | | +-- ZeroDivisionError
  14. | +-- AssertionError
  15. | +-- AttributeError
  16. | +-- EnvironmentError
  17. | | +-- IOError
  18. | | +-- OSError
  19. | | +-- WindowsError (Windows)
  20. | | +-- VMSError (VMS)
  21. | +-- EOFError
  22. | +-- ImportError
  23. | +-- LookupError
  24. | | +-- IndexError
  25. | | +-- KeyError
  26. | +-- MemoryError
  27. | +-- NameError
  28. | | +-- UnboundLocalError
  29. | +-- ReferenceError
  30. | +-- RuntimeError
  31. | | +-- NotImplementedError
  32. | +-- SyntaxError
  33. | | +-- IndentationError
  34. | | +-- TabError
  35. | +-- SystemError
  36. | +-- TypeError
  37. | +-- ValueError
  38. | +-- UnicodeError
  39. | +-- UnicodeDecodeError
  40. | +-- UnicodeEncodeError
  41. | +-- UnicodeTranslateError
  42. +-- Warning
  43. +-- DeprecationWarning
  44. +-- PendingDeprecationWarning
  45. +-- RuntimeWarning
  46. +-- SyntaxWarning
  47. +-- UserWarning
  48. +-- FutureWarning
  49. +-- ImportWarning
  50. +-- UnicodeWarning
  51. +-- BytesWarning

For a detailed description of each of them, refer to the official Python documentation.

web2py exposes only one new exception, called HTTP. When raised, it causes the program to return an HTTP error page (for more on this refer to Chapter 4).

Any object can be raised as an exception, but it is good practice to raise objects that extend one of the built-in exception classes.