zoukankan      html  css  js  c++  java
  • 异常处理

    异常处理:
    例1:
      data1 = {}
      data2 = []
    try:
      print(data2[1])
      data1["name"]
    except KeyError as e:
      print("no key:", e)
    except IndexError as e:
      print("list index error:", e)
     
    等同:

    data1 = {}
    data2 = []
    try:
      print(data2[1])
      data1["name"]
    except(KeyError, IndexError) as e:
      print("no key:", e)
       
       
    例2:except Exception  所有的错误都可以抓:不建议用
      
    try:
      print(data2[1])
      data1["name"]
    except Exception as e:
      print("no key:", e)
      
    例3:
    data1 = {"name":"brace"}
    data2 = [1,2]
    try:
      print(data2[1])
      data1["name"]
    except KeyError as e:
      print("no key:", e)
    except IndexError as e:
      print("list index error:", e)
    except Exception as e:
      print("no key:", e)
    else:
      print("一切正常才执行")
    finally:
      print("不管有没错都执行")
        
    自定义异常:
     
    class BraceException(Exception):
    def __init__(self, msg):
       self.message = msg
     
    def __str__(self):
      return self.message
    try:
      raise BraceException("数据库连接不上!")
    except BraceException as e:
        print(e)
     
     输出:
        数据库连接不上!
      
      
     class BraceException(Exception):
     
      def __init__(self, msg):
       self.message = msg
     
      def __str__(self):
       return "XXXXXXXXXXXX"
     try:
      raise BraceException("数据库连接不上!")
     except BraceException as e:
      print(e)
     
     输出:
      XXXXXXXXXX
  • 相关阅读:
    spark连接MongoDB
    idea+scala+spark遇到的一些问题
    linux环境变量的配置
    sqoop的导入导出
    hive中一些常用的sql语句
    Unity 插件制作笔记(持续更新)
    linux-shutdown命令说明
    linux中的redis缓存服务器
    IceScrum敏捷开发工具的安装文档-官方最新版
    PHP设计模式系列
  • 原文地址:https://www.cnblogs.com/brace2011/p/9291579.html
Copyright © 2011-2022 走看看