Python基础教程

006_raise主动触发异常

raise主动触发异常

Python系统会自动检查异常。

assert可以设置条件,如果条件不成立则会触发AssertionError异常。

raise可以主动触发任何异常,我们能控制发生异常的时机。

raise主动触发异常

Python 使用 raise 语句触发一个指定的异常,包括自定义异常。

raise语法格式如下:

raise [Exception [, args [, traceback]]]

示例程序如下

print("hello")
raise Exception("想什么时候触发异常都能办到")
print("world")

运行结果

C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t33.py
hello
Traceback (most recent call last):
  File "E:/wkp01/p00/test01/atestpkg/t33.py", line 2, in <module>
    raise Exception("想什么时候触发异常都能办到")
Exception: 想什么时候触发异常都能办到

Process finished with exit code 1

raise触发异常与try...except配合使用

raise触发异常与try...except配合使用示例如下

import traceback

# 定义除法函数
def divi(x,y):
    try:
        if x<y:
            raise Exception("当x<y时发生异常")
        z=x/y
        return z
    except Exception as e:
        print("发生了assert异常")
        print(e)
        print(traceback.format_exc())

res=divi(6,2)
print(res)
res=divi(2,6)
print(res)

运行结果

C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t32.py
3.0
发生了assert异常
当x<y时发生异常
Traceback (most recent call last):
  File "E:/wkp01/p00/test01/atestpkg/t32.py", line 7, in divi
    raise Exception("当x<y时发生异常")
Exception: 当x<y时发生异常

None

Process finished with exit code 0
这篇文章对您有用吗? 1

我们要如何帮助您?