The Python Tutorial 8——Errors and Exceptions
2014-12-05 16:43
316 查看
两类错误:语法或者是逻辑 syntax errors and exceptions.
the arrow: in the example, the error is detected at the keywordprint,
since a colon(':') is missing before it. File name and line number are printed so youknow where to look in case the input came from a script.
Python programs.
The
try statement works as follows. 处理流程
First, the try clause (the statement(s) between the
try andexcept
keywords) is executed.
If no exception occurs, the except clause is skipped and execution of thetry
statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause isskipped. Then if its typematches the exception named after the
except keyword, the except clause is executed, and then execution continues after thetry
statement.
If an exception occurs which does not match the exception named in the except clause, it is passed on to outertry
statements; if no handler isfound, it is anunhandled exception and execution stops with a message as shown above.
A
try statement may havemore than one except clause, to specify handlers for different exceptions.At most one handler
will be executed.Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the sametry
statement. An except clause mayname multiple exceptions as a parenthe sizedtuple, for example:
The last except clause may omit the exception name(s), to serve as a wildcard.Use this with extreme caution, since it is easy to mask a real programming error in this way! It can also
be used to print an error message and then re-raise the exception (allowing a caller to handle the exception as well):
try ...except
statement has an optionalelse clause, which, when present,must follow all except clauses. It is useful for code thatmust be executed if the try
clause does not raise an exception. Forexample:
raise statement allows the programmer to force a specifiedexception to occur. For example:
The sole argument to
raise indicates the exception to be raised.This must be either an
exception instance or an exception class (a class thatderives from Exception).
Most exceptions are defined with names that end in “Error,” similar to the naming of the standard exceptions.
try statement, whether an exception has occurred or not. finally语句总会执行,如果出现except语句未处理的异常则重新抛出异常。
As you can see, the
finally clause is executed in any event. The
TypeError raised by dividing two strings is not handled by the
except clause and therefore
re-raised after the
finally clause has been executed.
In real world applications, the
finally clause is useful for
releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.
8.1. Syntax Errors
>>> while True print 'Hello world' File "<stdin>", line 1, in ? while True print 'Hello world' ^ SyntaxError: invalid syntaxThe parser repeats the offending line and displays a little ‘arrow’ pointing atthe earliest point in the line where the error was detected. The error is caused by (or at least detected at) the tokenpreceding
the arrow: in the example, the error is detected at the keywordprint,
since a colon(':') is missing before it. File name and line number are printed so youknow where to look in case the input came from a script.
8.2. Exceptions
Even if a statement or expression is syntactically correct, it may cause anerror when an attempt is made to execute it. Errors detected during executionare calledexceptions and are not unconditionally fatal: you will soon learnhow to handle them inPython programs.
>>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in ? ZeroDivisionError: integer division or modulo by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects
8.3. Handling Exceptions
异常处理使用try except语句>>> while True: ... try: ... x = int(raw_input("Please enter a number: ")) ... break ... except ValueError: ... print "Oops! That was no valid number. Try again..." ...
The
try statement works as follows. 处理流程
First, the try clause (the statement(s) between the
try andexcept
keywords) is executed.
If no exception occurs, the except clause is skipped and execution of thetry
statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause isskipped. Then if its typematches the exception named after the
except keyword, the except clause is executed, and then execution continues after thetry
statement.
If an exception occurs which does not match the exception named in the except clause, it is passed on to outertry
statements; if no handler isfound, it is anunhandled exception and execution stops with a message as shown above.
A
try statement may havemore than one except clause, to specify handlers for different exceptions.At most one handler
will be executed.Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the sametry
statement. An except clause mayname multiple exceptions as a parenthe sizedtuple, for example:
... except (RuntimeError, TypeError, NameError): ... pass
The last except clause may omit the exception name(s), to serve as a wildcard.Use this with extreme caution, since it is easy to mask a real programming error in this way! It can also
be used to print an error message and then re-raise the exception (allowing a caller to handle the exception as well):
import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) except ValueError: print "Could not convert data to an integer." except: print "Unexpected error:", sys.exc_info()[0] raiseThe
try ...except
statement has an optionalelse clause, which, when present,must follow all except clauses. It is useful for code thatmust be executed if the try
clause does not raise an exception. Forexample:
for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close()
8.4. Raising Exceptions
Theraise statement allows the programmer to force a specifiedexception to occur. For example:
>>> raise NameError('HiThere') Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: HiThere
The sole argument to
raise indicates the exception to be raised.This must be either an
exception instance or an exception class (a class thatderives from Exception).
8.5. User-defined Exceptions
用户可以通过继承Exception类定义自己的异常类>>> class MyError(Exception): ... def __init__(self, value): ... self.value = value ... def __str__(self): ... return repr(self.value) ... >>> try: ... raise MyError(2*2) ... except MyError as e: ... print 'My exception occurred, value:', e.value ... My exception occurred, value: 4 >>> raise MyError('oops!') Traceback (most recent call last): File "<stdin>", line 1, in ? __main__.MyError: 'oops!'
Most exceptions are defined with names that end in “Error,” similar to the naming of the standard exceptions.
8.6. Defining Clean-up Actions
A finally clause is always executed before leaving thetry statement, whether an exception has occurred or not. finally语句总会执行,如果出现except语句未处理的异常则重新抛出异常。
>>> def divide(x, y): ... try: ... result = x / y ... except ZeroDivisionError: ... print "division by zero!" ... else: ... print "result is", result ... finally: ... print "executing finally clause" ... >>> divide(2, 1) result is 2 executing finally clause >>> divide(2, 0) division by zero! executing finally clause >>> divide("2", "1") executing finally clause Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str'
As you can see, the
finally clause is executed in any event. The
TypeError raised by dividing two strings is not handled by the
except clause and therefore
re-raised after the
finally clause has been executed.
In real world applications, the
finally clause is useful for
releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.
try: f = open('xxx') except: print 'fail to open' exit(-1) try: do something except: do something finally: f.close()参照点击打开链接
8.7. Predefined Clean-up Actions
with open("myfile.txt") as f: for line in f: print line,with as 语句 Python特有 可参照上面的链接
相关文章推荐
- The Python Tutorial 3.2 - 8Errors and Exceptions(错误和异常)
- Python Tutorial 学习笔记6 --Errors and Exceptions
- python tutorial 学习笔记(七)Errors and Exceptions
- Python Errors and Exceptions
- The Python Tutorial - Input and Output
- Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web and Enterprise App
- Python Errors and Exceptions
- Python Errors and Exceptions
- The Python Tutorial 7——Input and Output
- python-Errors and Exceptions--已阅
- Selenium Two Tutorial using IronPython and InternetExplorerDriver - The Automated Tester
- The Python Tutorial 3.2-4 More Control Flow Tools(深入控制流)
- The Python Tutorial » 5. Data Structures 小记
- Python Development with PyDev and Eclipse - Tutorial
- Extending and Embedding the Python Interpreter¶
- The Python Tutorial 3.2-3 An Informal Introduction to Python(Python简介)
- The Python Tutorial 3.2-6Modules(模块)
- The Python Tutorial 9. Classes
- The Python Tutorial 3.2-2使用Python解释器
- PL/SQL and Python scripts for the same function