异常处理在任何一门编程语言里都是值得关注的一个话题,良好的异常处理可以让你的程序更加健壮,清晰的错误信息更能帮助你快速修复问题。在Python中,和不部分高级语言一样,使用了try/except/finally语句块来处理异常,如果你有其他编程语言的经验,实践起来并不难。
异常处理语句 try...excpet...finally
实例代码
def div(a, b): try: print(a / b) except ZeroDivisionError: print("Error: b should not be 0 !!") except Exception as e: print("Unexpected Error: {}".format(e)) else: print('Run into else only when everything goes well') finally: print('Always run into finally block.') # tests div(2, 0) div(2, 'bad type') div(1, 2) # Mutiple exception in one line try: print(a / b) except (ZeroDivisionError, TypeError) as e: print(e) # Except block is optional when there is finally try: open(database) finally: close(database) # catch all errors and log it try: do_work() except: # get detail from logging module logging.exception('Exception caught!') # get detail from sys.exc_info() method error_type, error_value, trace_back = sys.exc_info() print(error_value) raise
总结如下
except
语句不是必须的,finally
语句也不是必须的,但是二者必须要有一个,否则就没有try
的意义了。except
语句可以有多个,Python会按except
语句的顺序依次匹配你指定的异常,如果异常已经处理就不会再进入后面的except
语句。</