>>> chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> chars[8]
...
IndexError: list index out of range
>>> 10 * (1/0)
...
ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3
...
NameError: name 'spam' is not defined
>>> '2' + 2
...
TypeError: cannot concatenate 'str' and 'int' objects
>>> open('data')
...
IOError: [Errno 2] No such file or directory: 'data'
TypeError and ZeroDivisionError.
try statement, which has this form (among others):
try: statements except exception_type: statements
try statement works as follows.
try clause (the statements between the try and except keywords) is executed.except clause (the statements after except) is skipped, and execution of the try statement is finished.
try clause, the rest of the clause is skipped, and if the exception's type matches the exception type after except, the except clause is executed.
try statements there might be.
If no handler is found for the exception, execution is interrupted and an error message is printed out.
>>> while True:
... try:
... x = int(input("Please enter a number: "))
... break
... except ValueError:
... print("Oops! That wasn't a valid number. Try again...")
...
Please enter a number: abc
Oops! That wasn't a valid number. Try again...
Please enter a number: 8*8
Oops! That wasn't a valid number. Try again...
Please enter a number: 88
except clauses, for different types of exceptions,
or the types can all be included in a tuple after the except.
...
except (ValueError, NameError, ZeroDivisionError):
pass
ZeroDivisionError as the exception type.)
IndexError as the exception type.)
IOError as the exception type.)
raise statement.
A raise statement looks like this:
raise exception_instanceor
raise exception_type. A simple way to make an exception instance is like this:
exception_type(string). The string prints out when the exception is raised.
class Word(object):
def add_pos(self, pos):
if pos not in ['n', 'v', 'a', 'adv', 'prep', 'conj']:
raise Exception(pos + ' is not a valid POS')
self.pos = pos
>>> =========================================================
>>> w = Word()
>>> w.add_pos('postp')
Traceback (most recent call last):
File "", line 1, in
w.add_pos('part')
File "", line 5, in add_pos
raise Exception(pos + ' is not a valid POS')
Exception: postp is not a valid POS