Python的try… excep异常捕捉机制

Python的try… excep异常捕捉机制Python 的 try excep 异常捕捉机制一 没有加入异常捕捉机制二 加入 try except 异常捕捉 1 已知错误类型 例如下面已知列表索引错误类型 IndexError 2 未知异

大家好,欢迎来到IT知识分享网。


异常:
异常即非正常状态,在Python中使用异常对象来表示异常。若程序在编译或运行过程中发生错误,程序的执行过程就会发生改变,抛出异常对象,程序流进入异常处理。如果异常对象没有被处理或捕捉,程序就会执行回溯(Traceback)来终止程序。



1、发生异常,不做处理:

def test_expect(): ll = ["one", "two", "three"] print(ll[3]) if __name__ == '__main__': test_expect() 

错误异常信息如下:

Traceback (most recent call last): File "D:/ZF/1_ZF_proj/python跳过异常继续执行.py", line 80, in <module> test_expect() File "D:/ZF/1_ZF_proj/python跳过异常继续执行.py", line 67, in test_expect print(ll[3]) IndexError: list index out of range 

2、使用try…except没有发生异常

def test_expect(): ll = ["one", "two", "three"] try: print("没有发生异常:------------------") print(ll[2]) print("发生异常,这里不执行:") except Exception as e: print("只有try中发生异常,except才会执行") if __name__ == '__main__': test_expect() 

没有发生异常输出结果如下(只要没有发生异常,except中的语句就不会被执行):

D:\software_install\Anaconda_install\python.exe D:/ZF/1_ZF_proj/python跳过异常继续执行.py 没有发生异常:------------------ three 发生异常,这里不执行: 

3、使用try…except发生异常

def test_expect(): ll = ["one", "two", "three"] try: print("没有发生异常:------------------") print(ll[6]) print("发生异常,这里不执行:") except Exception as e: print("只有try中发生异常,except才会执行") if __name__ == '__main__': test_expect() 

发生异常输出结果如下(只要发生异常,就会从try发生异常的位置,跳到except语句中执行):

D:\software_install\Anaconda_install\python.exe D:/ZF/1_ZF_proj/python跳过异常继续执行.py 没有发生异常:------------------ 只有try中发生异常,except才会执行 

4、查看异常信息的输出

一、没有加入异常捕捉机制

test_list = [1, 2] print(test_list[3]) 

执行之后,会在控制台输出:IndexError 错误, 意思是超过了列表的索引范围
在这里插入图片描述

二、加入try … except 异常捕捉

1、已知错误类型 (例如下面已知列表索引错误类型IndexError

下面以一个列表索引的例子来讲述 try... except的用法
1、异常类型起别名

import logging logging.basicConfig(level=logging.INFO, filename='Error.log', format='%(asctime)s - %(message)s') test_list = [1, 2] try: print(test_list[2]) except IndexError as e: logging.error("索引越界:%s" % e) 

我们知道捕捉的异常类型是IndexError 测试可以直接在except后面加上异常类型
在这里插入图片描述
在日志中保存捕捉的异常信息,Error.log 中保存的异常信息如下:

2019-04-18 14:24:19,109 - 索引越界:list index out of range

2、异常类型不起别名

import logging logging.basicConfig(level=logging.INFO, filename='Error.log', format='%(asctime)s - %(message)s') test_list = [1, 2] try: print(test_list[2]) except IndexError: logging.error("索引越界:%s" % IndexError) 

在这里插入图片描述

在日志中保存捕捉的异常信息,Error.log 中保存的异常信息如下:

2019-04-18 14:36:47,177 - 索引越界:<class 'IndexError'>

3、把异常的类型和错误信息都输出

import logging logging.basicConfig(level=logging.INFO, filename='Error.log', format='%(asctime)s - %(message)s') test_list = [1, 2] try: print(test_list[2]) except IndexError as e: logging.error("索引越界:%s" % IndexError) # 输出错误的类型 logging.error("索引越界:%s" % e) # 输出错误的信息 

在日志中保存捕捉的异常信息,Error.log 中保存的异常信息如下:

2019-04-18 14:39:11,863 - 索引越界:<class 'IndexError'>
2019-04-18 14:39:11,863 - 索引越界:list index out of range

2、未知异常的类型

有些异常类型可能我们在事先之前并不知道,应该步捕捉呢,此时可以用 Exception 代替未知的异常类型,也就是Exception 和 IndexError其实就是等价的啦,只是我们看代码没有明显说明是什么异常类型而已

举例:

import logging logging.basicConfig(level=logging.INFO, filename='Error.log', format='%(asctime)s - %(message)s') test_list = [1, 2] try: print(test_list[2]) except Exception as e: logging.error("索引越界:%s" % IndexError) logging.error("索引越界:%s" % e) 

在这里插入图片描述
在日志中保存捕捉的异常信息,Error.log 中保存的异常信息如下:

2019-04-18 14:50:49,419 - 索引越界:<class 'IndexError'>
2019-04-18 14:50:49,419 - 索引越界:list index out of range

三、try … except … else … finally 使用

try:

except:

else: 只有不发生异常才会执行

finally: 无论是否发生异常都会执行

import logging logging.basicConfig(level=logging.INFO, filename='Error.log', format='%(asctime)s - %(message)s - %(module)s.py') test_list = [1, 2] try: print(test_list[3]) except Exception as e: logging.error("索引越界:%s" % IndexError) logging.error("索引越界:%s" % e) else: logging.info("只有不发生异常才会执行") # 程序不报错才会执行 finally: logging.info("无论是否发生异常都会执行") # 程序报不报错都会执行 print("捕捉到错误,这里也是会执行的") 

把异常的信息记录到日志中,之后下面的代码还会继续执行

在这里插入图片描述
在日志中保存捕捉的异常信息,Error.log 中保存的异常信息如下:

2019-04-18 19:06:26,820 - 索引越界:<class 'IndexError'> - error_catch.py
2019-04-18 19:06:26,821 - 索引越界:list index out of range - error_catch.py
2019-04-18 19:06:26,821 - 无论是否发生异常都会执行 - error_catch.py

四、logging模块调用异常捕捉方法,保存异常信息日志

logging模块,有两个方法可以直接保存异常的日志信息

  • logging.error()
  • logging.exception()
    两个方法的文档:
def error(msg, *args, kwargs): """ Log a message with severity 'ERROR' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.error(msg, *args, kwargs) def exception(msg, *args, exc_info=True, kwargs): """ Log a message with severity 'ERROR' on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format. """ error(msg, *args, exc_info=exc_info, kwargs) 

2、例子

import logging logging.basicConfig(level=logging.INFO, filename='Error.log', format='%(asctime)s - %(message)s - %(module)s.py') test_list = [1, 2] try: print(test_list[2]) except Exception as e: logging.error(e) logging.info("----------------------------------------") logging.exception(e) print("捕捉到错误,这里也是会执行的") 

在这里插入图片描述
在日志中保存捕捉的异常信息,Error.log 中保存的异常信息如下:
从日志内容可以看出:

  • logging.error(): 输出的是简短的异常信息
  • logging.exception():输出的是详细的异常信息
    在这里插入图片描述

五、常用的异常类型表

异常 描述
BaseException 所有异常的基类
SystemExit 解释器请求退出
KeyboardInterrupt 用户中断执行(通常是输入^C)
Exception 常规错误的基类
StopIteration 迭代器没有更多的值
GeneratorExit 生成器(generator)发生异常来通知退出
StandardError 所有的内建标准异常的基类
ArithmeticError 所有数值计算错误的基类
FloatingPointError 浮点计算错误
OverflowError 数值运算超出最大限制
ZeroDivisionError 除(或取模)零 (所有数据类型)
AssertionError 断言语句失败
AttributeError 对象没有这个属性
EOFError 没有内建输入,到达EOF 标记
EnvironmentError 操作系统错误的基类
IOError 输入/输出操作失败
OSError 操作系统错误
WindowsError 系统调用失败
ImportError 导入模块/对象失败
LookupError 无效数据查询的基类
IndexError 序列中没有此索引(index)
KeyError 映射中没有这个键
MemoryError 内存溢出错误(对于Python 解释器不是致命的)
NameError 未声明/初始化对象 (没有属性)
UnboundLocalError 访问未初始化的本地变量
ReferenceError 弱引用(Weak reference)试图访问已经垃圾回收了的对象
RuntimeError 一般的运行时错误
NotImplementedError 尚未实现的方法
SyntaxError Python 语法错误
IndentationError 缩进错误
TabError Tab 和空格混用
SystemError 一般的解释器系统错误
TypeError 对类型无效的操作
ValueError 传入无效的参数
UnicodeError Unicode 相关的错误
UnicodeDecodeError Unicode 解码时的错误
UnicodeEncodeError Unicode 编码时错误
UnicodeTranslateError Unicode 转换时错误
Warning 警告的基类
DeprecationWarning 关于被弃用的特征的警告
FutureWarning 关于构造将来语义会有改变的警告
OverflowWarning 旧的关于自动提升为长整型(long)的警告
PendingDeprecationWarning 关于特性将会被废弃的警告
RuntimeWarning 可疑的运行时行为(runtime behavior)的警告
SyntaxWarning 可疑的语法的警告
UserWarning 用户代码生成的警告
Exception类:是通用异常基类下列异常类均继承于Exception类,Python解析器会自动将通用异常类型名称放在内建命名空间中,所以当使用通用异常类型时,不需要import exceptions模块。

参考:
1、https://blog.csdn.net/zongxp/article/details/
2、http://www.runoob.com/python/python-exceptions.html

在这里插入图片描述


在这里插入图片描述


在这里插入图片描述
♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/144410.html

(0)
上一篇 2025-04-26 20:45
下一篇 2025-04-26 21:10

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信