学习笔记

1、什么是异常处理

Python用异常对象(exception object)表示异常情况,遇到错误后,会引发异常。如果异常对象并未被处理或捕捉,程序就会用所谓的回溯(Traceback,一种错误信息)终止执行

2、raise的基本格式

raise的基本格式:

raise [exceptionName [(reason)]]

其中,用 [] 括起来的为可选参数,其作用是指定抛出的异常名称,以及异常信息的相关描述。如果可选参数全部省略,则 raise 会把当前错误原样抛出;如果仅省略 (reason),则在抛出异常时,将不附带任何的异常描述信息。

即以下三种情况:

1、raise

2、raise exceptionName

3、raise exceptionName (reason)

参考资料:Python raise用法(超级详细,看了无师自通)

3、raise的三种情况

1)、单独一个 raise。

单独的raise会重新触发前一个异常,如果之前没有触发异常,触发RuntimeError。

第一种情况:上下文中捕获的异常:

由raise抛出本身代码中存在的异常

def test(num):
    try:
        100/num
    except Exception as res:
        print("捕获异常完成")
        raise  
test(0)

运行结果:

第二种情况:默认引发RuntimeError 异常:

def test(num):
    if num == 100:
        raise
    print(num)
test(100)

运行结果:

 2)raise 异常名称

def Test1(num):
    try:
        100/num
    except Exception as res:
        print("捕获异常完成")
        print(res)
        raise ZeroDivisionError
        print("----在raise之后,不会执行-----")
    else:
        print("没有异常")
Test1(0)

运行结果:

其中 异常名称可以为自定义异常名称 

class CustomException(Exception):
    def __init__(self,ErrorInfo):
        self.ErrorInfo = ErrorInfo
    def __str__(self):
        return self.ErrorInfo
def Test1(num):
    try:
        raise CustomException('这是一个自定义的异常')
    except CustomException as res:
        print(res)
Test1(0)

运行结果:

 

 

 

3)、raise 异常名称(异常描述信息)

def Test1(num):
    try:
        100/num
    except Exception as res:
        print("捕获异常完成")
        print(res)
        raise ZeroDivisionError("分母不能为0")
        print("----在raise之后,不会执行-----")
    else:
        print("没有异常")
Test1(0)

运行结果

物联沃分享整理
物联沃-IOTWORD物联网 » Python的raise用法

发表评论