try...except...else...finally
Python can throw - pardon, raise - Exceptions:
>>> try:
... a = 1 / 0
... except Exception as e:
... print 'oops: %s' % e
... else:
... print 'no problem here'
... finally:
... print 'done'
...
oops: integer division or modulo by zero
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:
>>> try:
... raise TypeError()
... except ValueError:
... print 'value error'
... except Exception:
... print 'generic error'
...
generic error
The else
and finally
clauses are optional.
Here is a list of built-in Python exceptions + HTTP (defined by web2py)
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- HTTP (defined by web2py)
+-- 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
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.