python(异常)

异常

a = [1,2,3]
print(a[8])
try:
# 执行里面的代码
print(“执行try”)
print(a[7])
except:
# 如果try里语句执行时,执行里面的代码
print(“出错了”)
else:
# 如果try里语句执行时,没有错误时则执行
print(“没有错”)
finally:
# 不管有没有出错,都会执行
print(“最后执行”)
执行结果:
执行try
出错了
最后执行

注意:
1.捕获正确的异常(要知道有哪些问题,分析问题,得到这些问题会抛出的指定异常)
2.异常的处理,要合理,要有日志

补充:
1.如果不知道会出现什么样的异常,可以在异常中加入以下代码:
exc = sys.exc_info() # exc返回一个元组
print (exc)
2.日志
import logging
logger = logging.getLogger() # 创建日志的对象
logfile = ‘test.log’
hdlr = logging.FileHandler(r’C:\Users\Administrator\Desktop\001\sendlog.txt’) # 存放文件(基于文件)
formatter = logging.Formatter(’%(asctime)s %(levelname)s %(message)s’) # 输出格式:时间,等级,内置信息
hdlr.setFormatter(formatter) # 导入格式
logger.addHandler(hdlr) # 日志对象和文件对象绑定
logger.setLevel(logging.NOTSET) # 设置日志级别
logger.debug(“gagagagagagagagagagagag”)
注意:
1日志文件的模式是追加
2日志的等级有三种:logging.debug(日志调试), logging.error(致命的错误),logging.info(记录程序运行的情况)
断言
定义:一种开发时期时检定代码的方式,只断言绝对不能出现的错误
格式
assert “表达式” , “出错以后抛出的message”
断言使用原则:先断言绝对不能出的错误,然后再去处理错误(异常)
自定义异常
class myException(Exception):
def init(self, error, msg):
self.args = (error , msg)
self.error = error
self.msg = msg
raise myException(“Error”,11111 )
实行结果:
Traceback (most recent call last):
File “E:/project/test1.py”, line 63, in
raise myException(“Error”,11111 )
main.myException: (‘Error’, 11111)

注解:raise:抛出一个异常

猜你喜欢

转载自blog.csdn.net/weixin_42970234/article/details/84575607
今日推荐