python 异常处理

异常处理

import os
# 这是用函数的形式去设定异常
def fun(path,perv):
    "去path路径的文件 找到前缀为perv的一行数据获取数据并返回给调用者"
   response={"code":100,"data":None}
   try:
       if not os.path.exists(path):
           response["code"]=200              #    "文件不存在"  对于的代号
           response["data"]="文件不存在"
           return  response
       if not perv:
           response["code"]=300              #    文件不能空  对于的代号
           response["data"]="文件不能空"
           return  response
       pass
   except Exception as e:
       response["code"] = 666666       #    "未知错误" 对于的代号
       response["data"] = "未知错误"

   return    response
# 用类的形式去定义抛出异常
# 自定义 异常类 1
class MyException(Exception):# 去继承Exception类
    def __init__(self,code,msg):
        self.code=code
        self.msg=msg

try:
    raise MyException(1000,"操作正常")

except MyException as obj:
      print(obj.code,obj.msg)
自定义 异常类 2
class MyException(Exception):# 去继承Exception类
    def __init__(self,code,msg):
        self.code=code
        self.msg=msg
try:
    raise MyException(1000,"操作正常")
except MyException as e:
      print(e.code,e.msg)
# 自定义 异常类 3
class MyException(Exception):# 去继承Exception类
    def __init__(self,code,msg):
        self.code=code
        self.msg=msg
try:
    raise MyException(1000,"操作正常")

except  KeyError as obj:
      print(obj,111111)

except MyException as obj:
      print(obj,22222)

except Exception as obj:
      print(obj,33333)
# 主动触发异常
try:
    raise Exception('错误了。。。')
except Exception as e:
  print(e)
原文地址:https://www.cnblogs.com/Sup-to/p/11108481.html