您现在的位置是:网站首页> 编程资料编程资料
python嵌套try...except如何使用详解_python_
2023-05-26
288人已围观
简介 python嵌套try...except如何使用详解_python_
引言
众所周知,在python中我们用try…except…来捕获异常,使用raise来抛出异常,但是多重的try…except…是如何使用的呢
前提
抛出异常
当调用raise进行抛出错误的时候,抛出错误的后面的代码不执行
def func(): print("hello") raise Exception("出现了错误") print("world") func() 打印的错误堆栈
如果抓取错误,就相当于if...else,并不会打断代码的执行
def func(): try: print("hello") raise Exception("出现了错误") except Exception as why: print(why) print("world") func() 自定义异常
自定义异常需要我们继承异常的类,包括一些框架中的异常的类,我们自定义异常的话都需要继承他们
class MyError(Exception): pass def say_hello(str): if str != "hello": raise MyError("传入的字符串不是hello") print("hello") say_hello("world") 异常对象
- Exception 是多有异常的父类,他会捕获所有的异常
- 其后面会跟一个as as后面的变量就是异常对象,异常对象是异常类实例化后得到的
多重try
如果是嵌套的try...except...的话,这一层raise的错误,会被上一层的try...except...进行捕获
补充:捕获异常的小方法
方法一:捕获所有异常
a=10 b=0 try: print (a/b) except Exception as e: print(Exception,":",e) finally: print ("always excute") 运行:
: division by zero
always excute
方法二:采用traceback模块查看异常
import traceback try: print ('here1:',5/2) print ('here2:',10/5) print ('here3:',10/0) except Exception as e: traceback.print_exc() 运行:
here1: 2.5
here2: 2.0
Traceback (most recent call last):
File "/Users/lilong/Desktop/online_release/try_except_use.py", line 59, in
print ('here3:',10/0)
ZeroDivisionError: division by zero
方法三:采用sys模块回溯最后的异常
import sys try: print ('here1:',5/2) print ('here2:',10/5) print ('here3:',10/0) except Exception as e: info=sys.exc_info() print (info[0],":",info[1]) 运行:
here1: 2.5
here2: 2.0: division by zero
注意:万能异常Exception
被检测的代码块抛出的异常有多种可能性,并且我们针对所有的异常类型都只用一种处理逻辑就可以了,那就使用Exception,除非要对每一特殊异常进行特殊处理。
总结
到此这篇关于python嵌套try...except如何使用的文章就介绍到这了,更多相关python嵌套try...except使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关内容
- slearn缺失值处理器之Imputer详析_python_
- Python使用random.shuffle()随机打乱字典排序_python_
- python读取Windows注册表的示例代码_python_
- Python re.findall中正则表达式(.*?)和参数re.S使用_python_
- Python re.split方法分割字符串的实现示例_python_
- Flask快速实现分页效果示例_python_
- python sys模块使用方法介绍_python_
- python os.path模块使用方法介绍_python_
- 安装出现:Requirement already satisfied解决办法_python_
- python os模块使用方法介绍_python_
