python3 study notes error handling

During the running of the program, if an error occurs, you can agree to return an error code in advance, so that you can know whether there is an error and the reason for the error. It is very common to return error codes in calls provided by the operating system. For example, a function that opens a file open()returns the file descriptor (that is, an integer) when successful, and returns when there is an error -1.

It is very inconvenient to use the error code to indicate whether there is an error, because the normal result that the function itself should return is mixed with the error code, so that the caller must use a lot of code to determine whether there is an error:

def foo():
    r = some_function()
    if r==(-1):
        return (-1)
    # do something
    return r

def bar():
    r = foo()
    if r==(-1):
        print('Error')
    else:
        pass

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324819754&siteId=291194637