本文最后更新于2014年11月15日,已超过 1 年没有更新,如果文章内容失效,还请反馈给我,谢谢!



except Exception:

The difference is, that the first one will also catch KeyboardInterrupt, SystemExit and stuff like that, which are derived directly from exceptions.BaseException, not exceptions.Exception.(上面的2个try-catch语句块的区别之处在于,第1个try-catch会捕捉类似于KeyboardInternet、SystemExit这样的异常——基本上所有的异常都包括进去了,这是因为except后面没有任何说明,因此直接继承的是exceptions.BaseException而不是exceptions.Exception)

See documentation for details:
• try statement —
• exceptions —

Handling Exceptions(处理异常)

It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising theKeyboardInterrupt exception.

>>> 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(try语句块的执行流程如下):

• First, the try clause (the statement(s) between the try and except keywords) is executed.(首先执行try后面的)
• If no exception occurs, the except clause is skipped and execution of the try statement is finished.(如果没有异常发生,则except里面的语句就不执行了,try语句块也就执行结束了)
• If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.(如果在try中发生了异常,则try里面剩下的部分就会被跳过不执行,如果except后面的异常类型和try里面引发的异常类型相同,则会执行except里面的语句,否则就会在try语句块执行之后抛出异常)
• 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 is found, it is an unhandled exception and execution stops with a message as shown above.(如果发生的异常和except后面指定的异常类型不一致,则异常就会被抛到try语句块之外,然后就会有上面那样的错误。)

A try statement may have more 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 same try statement. An except clause may name multiple exceptions as a parenthesized tuple(一个except语句可以通过tuple来指定多个异常类型), for example:

... except (RuntimeError, TypeError, NameError):
...     pass

Note that the parentheses around this tuple are required, because except ValueError, e: was the syntax used for what is normally written as except ValueError as e: in modern Python (described below). The old syntax is still supported for backwards compatibility. This means except RuntimeError, TypeError is not equivalent to except (RuntimeError, TypeError): but toexcept RuntimeError as TypeError: which is not what you want.

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
    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."
    print "Unexpected error:", sys.exc_info()[0]

The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:

for arg in sys.argv[1:]:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
        print arg, 'has', len(f.readlines()), 'lines'

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.
When an exception occurs, it may have an associated value, also known as the exception’s argument. The presence and type of the argument depend on the exception type.
The except clause may specify a variable after the exception name (or tuple). The variable is bound to an exception instance with the arguments stored in instance.args. For convenience, the exception instance defines __str__() so the arguments can be printed directly without having to reference .args.
One may also instantiate an exception first before raising it and add any attributes to it as desired.

>>> try:
...    raise Exception('spam', 'eggs')
... except Exception as inst:
...    print type(inst)     # the exception instance
...    print inst.args      # arguments stored in .args
...    print inst           # __str__ allows args to be printed directly
...    x, y = inst.args
...    print 'x =', x
...    print 'y =', y
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

If an exception has an argument, it is printed as the last part (‘detail’) of the message for unhandled exceptions.
Exception handlers don’t just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions that are called (even indirectly) in the try clause. For example:

>>> def this_fails():
...     x = 1/0
>>> try:
...     this_fails()
... except ZeroDivisionError as detail:
...     print 'Handling run-time error:', detail
Handling run-time error: integer division or modulo by zero


声明: 除非注明,ixyzero.com文章均为原创,转载请以链接形式标明本文地址,谢谢!

2 thoughts on “Python的异常处理”

  1. 在Python中如何优雅的捕获并打印错误和异常信息?
    import sys
    import traceback
    # …
    except IOError as e:
    print “I/O error({0}): {1}”.format(e.errno, e.strerror)
    except ValueError as e:
    print “ValueError({0}): {1}”.format(e.errno, e.strerror)
    print “Unexpected error:”, sys.exc_info()[0]
    print traceback.format_exc()


电子邮件地址不会被公开。 必填项已用*标注