python代码,如何使用try-except捕获到异常信息?
发布于 作者:苏南大叔 来源:程序如此灵动~
上一篇文章中,苏南大叔写了如何触发异常信息,因为异常信息会阻止代码继续执行,所以下一步可能需要一个try catch
来捕获这些异常。本文就是描述如何在python
代码中,进行异常信息捕获。
大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔和计算机代码的故事。本文记录python
下捕获异常的既定代码模式的使用方法。测试环境:win10
,python@3.6.8
。
基本写法
在其它的编程语言中,这个都是try catch
语句。但是,python
里面的同样功能语句叫做try except
。python
下异常捕获的代码,基本句式如下:
try:
# 可能出问题的代码
except:
# 对异常进行捕获,如果没捕获到,代码就在上一步就不执行了
else:
# 没有发生异常的话
finally:
# 无论是否发生异常都执行
最简单的情况就是这样:
try:
# 可能出问题的代码
except:
# 对异常进行捕获,如果没捕获到,代码就在上一步就不执行了
测试代码
测试代码:
try:
raise AssertionError('主动抛出的断言异常')
# raise TypeError
# except:
except Exception as err:
# except AssertionError as err:
# except (AssertionError,TypeError):
# except (AssertionError) as err:
print(err)
print("发生错误了")
else:
print("啥错误也没有发生")
finally:
print("无论如何都执行")
这里需要特别说明的是:异常不一定会被全部捕获的。如果有漏网之鱼的话,可能就会影响程序的继续执行。
Exception
可以捕获所有异常信息。Exception as err
可以将全部异常信息转化为错误字符串。(,)
可以列出具体的异常信息集合。() as err
可以将列表中的异常信息转化为错误字符串。
题外话
在php
里面,就一个try ... catch
。例如:
try{
//...
}
catch (Exception $exception){
//...
}
相关文章
- https://newsn.net/say/python-exception.html
- https://newsn.net/say/python-def.html
- https://newsn.net/say/python-decorators.html
综述
本文主要描述python
语言下try except
异常捕获的写法。更多python
语言的经验文章:


