目录
1. 基础格式
raise语句可以触发异常,用于直接抛出Python内置异常,或用户自定义的异常。
raise语句有如下几种形式:
raise
raise class [from (otherexce | None)]
raise instance [from (otherexce | None)]
2. raise 单独语句
单独使用 raise 语句,默认引发 RuntimeError 异常;
单独使用 raise 语句,也可以引发当前上下文中捕获的异常,譬如在 except 块中使用,可以直接触发已被捕获的异常。
#单独使用 raise 语句,默认引发 RuntimeError 异常
raise
Traceback (most recent call last):
File "<input>", line 1, in <module>
RuntimeError: No active exception to reraise
#在 except 块中单独使用 raise 语句,触发已被捕获的异常
try:
1/0
except:
raise
Traceback (most recent call last):
File "<input>", line 2, in <module>
ZeroDivisionError: division by zero
3. raise class
raise class,通常使用 raise 异常类型这样的结构,直接触发内置或自定义异常类型。
raise FileNotFoundError
Traceback (most recent call last):
File "<input>", line 1, in <module>
FileNotFoundError
raise OSError
Traceback (most recent call last):
File "<input>", line 1, in <module>
OSError
4. raise instance
raise instance,通常使用 raise 异常类型(描述信息) 这样的结构,触发内置或自定义异常,同时附带异常描述。
raise FileNotFoundError('文件无法找到!')
Traceback (most recent call last):
File "<input>", line 1, in <module>
FileNotFoundError: 文件无法找到!
raise OSError('系统错误!')
Traceback (most recent call last):
File "<input>", line 1, in <module>
OSError: 系统错误!
5. raise from
异常有时候能作为对其他异常的相应而触发,Python 支持 raise 语句拥有一个可选的 from 分句,语法结构如下:
raise newexception from otherexception
from 后面跟的表达式制定了另一个异常类或实例,该异常(即 otherexception)会附加到新印发异常(即 newexception)的__cause__属性。
raise OSError('系统错误!') from FileNotFoundError('文件无法找到!')
FileNotFoundError: 文件无法找到!
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<input>", line 1, in <module>
OSError: 系统错误!
6. try ... raise ... 多层循环跳出
对于多层嵌套循环,内层的 break、continue 只能跳出一层循环,当需要一次结束所有循环结构,可以使用 try ... raise ... 语句;
首先将多层嵌套循环结构放入 try suite 结构中;再在循环结构中需要跳出的位置写入 raise 触发异常;最后根据需要在 except 或 finally suite 中做跳出的后续处理。
x = 1
try:
while x > 0:
while x < 80:
for x in range(1,1000):
print(x)
if x > 5:
raiese
print('被跳过代码')
print('被跳过代码')
print('被跳过代码')
except:
print('直接跳出!')
1
2
3
4
5
6
直接跳出!

本文详细介绍了Python中的raise语句,包括基础格式、单独使用、指定异常类、附带描述信息以及利用`raise from`记录异常因果。此外,还探讨了如何在多层循环中通过`try ... raise ...`实现一次性跳出所有循环。

10万+

被折叠的 条评论
为什么被折叠?



