在python中捕获和处理特定的异常

问题描述 投票:0回答:2

我在Windows 10上运行Python 3.7。我尝试执行。

def A():
    try:
        # do something

    except Exception as e:
        print("Error: %s." % e)

def B():
    try:
        # do something else

    except Exception as e:
        print("Error: %s." % e)

我想 "捕捉 "一些特定的错误,比如: 404 Client Error 等,并将其发送给处理情况的函数,然后在代码中返回之前的状态。请问如何才能做到这一点?

非常感谢。

python exception try-catch
2个回答
0
投票
class ClientError(Exception):
    pass

def a():
    try:
        raise ClientError("boo!")
    except Exception as e:
        print(e)
    print("All fine now")

看看流程如何在 try-except 块?

>>> a()
boo!
All fine now

0
投票

我是这样做的,定义所有我关心的例外情况

class ClientException(Exception):
    pass

class Exception404(ClientException):
    pass

class Exception500(ClientException):
    pass

def A():
    try:
        # do something
        raise Exception404()
    except ClientException as e:
        print("Error: %s." % e)

def B():
    try:
        # do something else
        raise Exception500()
    except ClientException as e:
        print("Error: %s." % e)

所以,你将你的异常与相同的父类进行分组,并用共同的祖类来捕获它们。

© www.soinside.com 2019 - 2024. All rights reserved.