Python的异常处理


之前没怎么用“异常处理代码块”的习惯,一来是因为代码量较小、工程也不大,基本上各种问题都处于可控的状态下(我一般都是在完全调试好了之后才开始真正将代码放入crontab中定期执行的,没事的时候也会看看执行的结果是否符合预期,所以这样做了很久也没什么大的问题出现);二来是没这个习惯(没吃过这方面的亏……),觉得添加了这些“无用”的代码之后,显得有些冗余,不符合Python简洁的风格。

但是有时候在把代码交给别人的时候,因为前期你没办法清楚的知道代码要在一个什么样的环境下执行,也就没办法进行全面的分析、调试,所以,这时候之前的代码习惯就有问题了——出了问题没法处理,于是,开始在代码中加入了异常处理,下面是在学习过程中记录的一些内容,方便随时回顾:


try:
    doSomething()
except:
    pass
###or###
try:
    doSomething()
except Exception:
    pass

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 — http://docs.python.org/reference/compound_stmts.html#try
• exceptions — http://docs.python.org/library/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
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]
    raise

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:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
    else:
        print arg, 'has', len(f.readlines()), 'lines'
        f.close()

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

 

,

《 “Python的异常处理” 》 有 2 条评论

  1. 在Python中如何优雅的捕获并打印错误和异常信息?
    https://docs.python.org/2/tutorial/errors.html
    https://stackoverflow.com/questions/4690600/python-exception-message-capturing
    https://docs.python.org/2/library/traceback.html
    `
    import sys
    import traceback
    try:
    # …
    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)
    except:
    print “Unexpected error:”, sys.exc_info()[0]
    print traceback.format_exc()
    `

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注