做影视网站怎么挣钱,没建网站 备案,深圳网站设计南京,西安网站建设优化与推广1 python异常之raise语句
python通过raise语句显式触发异常#xff0c;raise后面跟类名或实例名。
1.1 基本用法
用法
raise 类名
raise 实例名
raise描述
#xff08;1#xff09; raise 类名#xff0c;则python自动调用类的不带参数的构造…1 python异常之raise语句
python通过raise语句显式触发异常raise后面跟类名或实例名。
1.1 基本用法
用法
raise 类名
raise 实例名
raise描述
1 raise 类名则python自动调用类的不带参数的构造函数来触发异常
2 raise 实例名触发指定实例名的异常
3 raise 重新触发当前异常通常用于异常处理器中传递已经捕获的异常
示例 try:raise TypeError
except TypeError:print(raise重新引发当前异常)raiseraise重新引发当前异常
Traceback (most recent call last):File pyshell#10, line 2, in moduleraise TypeError
TypeError1.2 raise from
raise from 用于描述当前异常与except捕获异常的关系。
用法
raise [异常[(异常说明)]]
raise 异常 from 变量
raise 异常 from None描述
在except分句编写raise时用于向外传递异常如果不接参数则传递except捕获的异常如果接参数则传递最新的异常并且说明与except捕获的异常的关系。
1 raise [异常[(‘异常说明’)]]表示raise的异常与except捕获的异常没有直接关系
2 raise 异常 from 变量表示raise的异常由except捕获的异常导致
3 raise 异常 from None不打印except捕获的异常
1.2.1 raise
描述
raise [异常[(‘异常说明’)]]表示raise的异常与except捕获的异常没有直接关系
示例 def testraise(s,i):try:print(s[i])except IndexError:raise ValueError(i输入错误) testraise(梯阅线条,5)
Traceback (most recent call last):File pyshell#17, line 3, in testraiseprint(s[i])
IndexError: string index out of range
# raise [异常[(异常说明)]] 捕获except的异常时触发了另一个异常raise的异常两者无直接关系
During handling of the above exception, another exception occurred:Traceback (most recent call last):File pyshell#18, line 1, in moduletestraise(梯阅线条,5)File pyshell#17, line 5, in testraiseraise ValueError(i输入错误)
ValueError: i输入错误1.2.2 raise from
描述
raise 异常 from 变量表示raise的异常由except捕获的异常导致
示例 def testraise(s,i):try:print(s[i])except IndexError as ie:raise ValueError(i输入错误) from ie testraise(梯阅线条,5)
Traceback (most recent call last):File pyshell#23, line 3, in testraiseprint(s[i])
IndexError: string index out of range# raise 异常 from except的异常 是由except异常直接引发的
The above exception was the direct cause of the following exception:Traceback (most recent call last):File pyshell#24, line 1, in moduletestraise(梯阅线条,5)File pyshell#23, line 5, in testraiseraise ValueError(i输入错误) from ie
ValueError: i输入错误1.2.3 raise from None
描述
raise 异常 from None不打印except捕获的异常
示例 def testraise(s,i):try:print(s[i])except IndexError as ie:# None 不打印 except的异常raise ValueError(i输入错误) from None testraise(梯阅线条,5)
Traceback (most recent call last):File pyshell#27, line 1, in moduletestraise(梯阅线条,5)File pyshell#26, line 5, in testraiseraise ValueError(i输入错误) from None
ValueError: i输入错误