Chapter 8 Errors and Exceptions
So far we have only mentioned the error message without discussing it in detail, if you run the previous example, you may have seen some error message. There are at least two different errors: syntactic errors and exceptions.
8.1 Syntax error
Syntactic errors, also known as grammatical analysis errors, are the most likely mistakes you make when learning Python.
>>> while 1 print 'Hello world'
File "<stdin>", line 1
while 1 print 'Hello world'
^
SyntaxError: invalid syntax
The parser repeats the error line and points to the earliest location of the error in the line with a small 'arrow'. The error is caused by the mark before the arrow (at least detected here). In this case, the error is detected at the keyword print because it should have a colon (":") in front of it. The error message shows the file name and line number so that if the error occurs in a script file, you will know where to look for it.
8.2 Exceptions
Even if there is no problem with the statement or expression syntax, an error may occur while trying to run it. The error detected at runtime is called exceptions, and this error is not necessarily fatal: you will soon learn how to handle exceptions in Python programs. However, most exceptions cannot be processed by the program, which can generate error messages such as:
>>> 10 * (1/0)
Traceback (innermost last):
File "<stdin>", line 1
ZeroDivisionError: integer division or modulo
>>> 4 + spam*3
Traceback (innermost last):
File "<stdin>", line 1
NameError: spam
>>> '2' + 2
Traceback (innermost last):
File "<stdin>", line 1
TypeError: illegal argument type for built-in operation
The last line of the error message shows what happened. Exceptions have different types, and the types are displayed as part of the error message: the types in the above example are ZeroDivisionError, NameError, and TypeError. The string displayed as an exception type is the built-in name of the exception that occurs. This holds true for all built-in exceptions, but not necessarily for user-defined exceptions (users are better off abide by such a convention). Standard exception names are built-in identifiers (not keywords reserved).
The rest of this line is a detail of the error, and its interpretation depends on the exception type. The part preceding the error message shows the context in which the error occurred in the form of stack anti-trace. Generally this includes a stack reverse trace of a source program line listing; however, it does not display the lines read from standard input.
The library reference manual lists built-in exceptions and their meanings.
8.3 Exception handling
The selected exception can be programmed. Please see the following example to show the reciprocal of some floating point numbers:
>>> numbers = [0.3333, 2.5, 0, 10]
>>> for x in numbers:
... print x,
... try:
... print 1.0 / x
... except ZeroDivisionError:
... print '*** has no inverse ***'
...
0.3333 3.00030003
2.5 0.4
0 *** has no inverse ***
10 0.1
The try statement works like this:
First, run the try clause (a statement between try and except).
If no exception occurs, skip the except clause and the try statement is run.
If an exception error occurs in the try clause and the exception error matches the exception name specified after except, skip the remaining part of the try clause, execute the except clause, and then continue to execute the program behind the try statement.
If an exception error occurs in the try clause but the exception error does not match the exception name specified after except, this exception is passed to the outer try statement. If no matching handler is found, this exception is called an unprocessed exception, the program stops running, and an error message is displayed.
The try statement can have multiple except clauses, specifying different processing for different exceptions. Only one error handler is executed at most. The error handler only handles exceptions that occur in the corresponding try clause, and the error handler will not react if exceptions occur in other error handlers in the same try statement. An exception clause can list multiple exceptions and be separated by commas in brackets, for example:
... except (RuntimeError, TypeError, NameError):
... pass
The last except clause can omit the exception name as a wildcard item. This method should be used with caution, as this may cause the program to actually make errors but cannot be discovered.
try ... The except statement has an optional else clause, which should be placed after all except clauses if any. else means that no exception occurs. We can put what we need to do when no exception occurs in the try clause. For example:
for arg in [1:]:
try:
f = open(arg, 'r')
except IOError:
print 'Cannot open', arg
else:
print arg, 'yes', len(()), 'way'
()
An exception may be accompanied by a value called an exception parameter. Whether the parameter exists and its type depends on the exception type. For exceptions with parameters, except, you can specify a variable after the exception name (or table) to accept exception parameter values, such as:
>>> try:
... spam()
... except NameError, x:
... print 'name', x, 'undefined'
...
name spam undefined
Exceptions with parameters are not processed and their parameter values are listed in the last details of the error message.
Exception handlers not only deal with exceptions that arise directly in a try clause, but also in functions called in a try clause (or even indirectly called functions). like:
>>> def this_fails():
... x = 1/0
...
>>> try:
... this_fails()
... except ZeroDivisionError, detail:
... print 'Handling run-time error:', detail
...
Handling run-time error: integer division or modulo
8.4 Exceptions are generated
The raise statement allows the programmer to force the specified exception. For example:
>>> raise NameError, 'HiThere'
Traceback (innermost last):
File "<stdin>", line 1
NameError: HiThere
The first parameter of the raise statement specifies the name of the exception to be generated. The optional second parameter specifies an exception parameter.
8.5 User-defined exceptions
You can define your own exceptions in the program, just assign a string to a variable. For example:
>>> my_exc = 'my_exc'
>>> try:
... raise my_exc, 2*2
... except my_exc, val:
... print 'My exception occurred, value:', val
...
My exception occurred, value: 4
>>> raise my_exc, 1
Traceback (innermost last):
File "<stdin>", line 1
my_exc: 1
Many standard modules use this method to report errors that occur in functions defined by themselves.
8.6 Define cleaning actions
There is another finally optional clause in the try statement, which can be used to specify actions to be performed regardless of whether it is wrong or not. For example:
>>> try:
... raise KeyboardInterrupt
... finally:
... print 'Goodbye, world!'
...
Goodbye, world!
Traceback (innermost last):
File "<stdin>", line 2
KeyboardInterrupt
The finally clause will be executed regardless of whether an exception occurs in the try clause. When an exception occurs, execute the finally clause first and then re-propose the exception. The final clause will also be executed when the try statement exits with a break or return statement.
It should be noted that if the try statement has the exception clause, it cannot have finally clauses, and if the finally clause is the last clause, it cannot use the except clause and the finally clause at the same time. If necessary, you can nest it.
Previous page12345678910Next pageRead the full text