zoukankan      html  css  js  c++  java
  • Python核心编程读笔 9: 异常

    第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.

          

          也可以用裸except语句(不推荐):

          try:

            try_suite;

          except:

            # 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]

  • 相关阅读:
    复杂json对应的实体类定义
    Hbase 根据rowkey批量读写
    Spark 分组聚合转Map 的方式
    idea本地连接访问hadoop集群的方法
    新版supperset连接druid数据源设置
    使用jdbc java 连接 sqlserver 2008数据库 需要注意的事项
    关于CrystalQuartz设置Cron匹配的时区问题~
    VS2010连接远程TFS2012项目问题
    关于ASP.NET SignalR的Group使用
    关于CodeFrist下EntityFramework5.0及其最新版本中枚举的使用
  • 原文地址:https://www.cnblogs.com/hansonwang99/p/4966532.html
Copyright © 2011-2022 走看看