简体   繁体   中英

catch and care specific exceptions in python

I'm running Python 3.7 on Windows 10. I try to execute:

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)

I want to "catch" some specific errors like 404 Client Error and others and send them to function that handles the situation and then return to the previous state in the code. How can I do that?

Many thanks.

class ClientError(Exception):
    pass

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

See how the flow continues after the try - except block?

>>> a()
boo!
All fine now

This is how I would do it
define all the exceptions I care about

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)

So you group your exceptions with the same parent classes and catch them with the common ancestor class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM