码迷,mamicode.com
首页 > 编程语言 > 详细

Python核心编程读笔 8: 异常

时间:2015-11-15 14:55:07      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

第10章 异常
一、异常
1 检测和处理异常
  (1)try-except语句
    try:
      try_suite #监控这里的异常
    except Exception[, reason]:
      except_suite #异常处理代码

  (2)“带有多个except的try语句”和“处理多个异常的except语句”
  (3)捕获所有异常
      try:
        :
      except Exception, e:
        # error occurred, log ‘e‘, etc.
  (4)异常参数
  (5)else子句和finally子句
  (6)try-except-else-finally:厨房一锅端
    try:
      try_suite
    except Exception1:
      suite_for_Exception1
    except (Exception2, Exception3, Exception4):
      suite_for_Exceptions_2_3_and_4
    except Exception5, Argument5:
      suite_for_Exception5_plus_argument
    except (Exception6, Exception7), Argument67:
      suite_for_Exceptions6_and_7_plus_argument
    except:
      suite_for_all_other_exceptions
    else:
      no_exceptions_detected_suite
    finally:
      always_execute_suite


2 上下文管理
    with语句:
      with context_expr [as var]:
        with_suite
    举例:
      with open(‘/etc/passwd‘, ‘r‘) as f:
        for eachLine in f:
          # ...do stuff with eachLine or f...

        注:无论的在这一段代码的开始,中间,还是结束时发生异常,会执行清理的代码,此外文件仍会被自动的关闭.

3 触发异常
  raise [SomeException [, args [, traceback]]]

4 标准异常

二、断言
  assert expression[, arguments]

Python核心编程读笔 8: 异常

标签:

原文地址:http://www.cnblogs.com/hansonwang99/p/4966532.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!