Python进阶 异常



我们可以使用三种方法来处理多个异常。
第一种方法需要把所有可能发生的异常放到一个元组里。像这样:

try:
    file = open('test.txt', 'rb')
except (IOError, EOFError) as e:
    print("An error occurred. {}".format(e.args[-1]))



对每个单独的异常在单独的except语句块中处理。

try:
    file = open('test.txt', 'rb')
except EOFError as e:
    print("An EOF error occurred.")
    raise e
except IOError as e:
    print("An error occurred.")
    raise e



捕获所有异常:

try:
    file = open('test.txt', 'rb')
except Exception:
    # 打印一些异常日志,如果你想要的话
    raise



包裹到finally从句中的代码不管异常是否触发都将会被执行。这可以被用来在脚本执行之后做清理工作。

try:
    file = open('test.txt', 'rb')
except IOError as e:
    print('An IOError occurred. {}'.format(e.args[-1]))
finally:
    print("This would be printed whether or not an exception occurred!")

# Output: An IOError occurred. No such file or directory
# This would be printed whether or not an exception occurred!



在没有触发异常的时候执行一些代码。这可以很轻松地通过一个else从句来达到。
else从句只会在没有异常的情况下执行,而且它会在finally语句之前执行。

try:
    print('I am sure no exception is going to occur!')
except Exception:
    print('exception')
else:
    # 这里的代码只会在try语句里没有触发异常时运行,
    # 但是这里的异常将 *不会* 被捕获
    print('This would only run if no exception occurs. And an error here '
          'would NOT be caught.')
finally:
    print('This would be printed in every case.')

# Output: I am sure no exception is going to occur!
# This would only run if no exception occurs.
# This would be printed in every case.
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一、简介 Python最强大的结构之一就是它的异常处理能力,所有的标准异常都使用类来实现,都是基类Exceptio...
    随风化作雨阅读 3,169评论 0 1
  • 一、错误和异常 1、错误 从软件方面来讲,错误通常是语法或逻辑上的。语法错误会导致程序代码不能被解释器解释,这些错...
    常大鹏阅读 1,674评论 0 6
  • Python异常处理 异常概念: 异常:就是不正常的情况,程序开发过程中错误和BUG都是补充正常的情况 异常发生的...
    youngkun阅读 1,000评论 0 4
  • 如果说奥地利和法国是咖啡馆之母,那么土耳其就是外祖母,因为人类历史上第一家咖啡馆是出现在在大马士革,1530年建立...
    何以笙歌阅读 379评论 0 0
  • 陈智涛阅读 194评论 0 0

友情链接更多精彩内容