White learn Python (19): base Exception Handling

Life is short, I chose Python

The foregoing Portal

White learn Python (1): Opening

White Science Python (2): basic data type (on)

White Science Python (3): fundamental data types (lower)

White Science Python (4): Variable Basic Operation

White Science Python (5): base operator (on)

White Science Python (6): base operator (lower)

White Science Python (7): based flow control (on)

White Science Python (8): the basis of flow control (lower)

White Science Python (9): basic data structure (list) (a)

White Science Python (10): basic data structure (list) (lower)

White Science Python (11): basic data structure (tuples)

White Science Python (12): basic data structure (dictionary) (a)

White Science Python (13): basic data structure (dictionary) (lower)

White Science Python (14): basic data structure (set) (a)

White Science Python (15): basic data structure (set) (lower)

White Science Python (16): the basic data type (function) (a)

White Science Python (17): the basic data type (function) (lower)

White learn Python (18): basic file operations

We've already written so much sample code, and error message for you students may have been commonplace, today we have to talk about error handling information.

First, the program running in the process, resulting in abnormal, then, we may have two ideas. The first is for this exception do some special treatment to downgrade handler; the second is to program ignore this exception to continue execution, this exception may not interfere with the implementation of the main logic.

That this time, how do we do?

Programming experience students come to mind, then we went to try it ah, in Python, we can also go try it, understand it has been very clear, the following content is to try to perform from the literal meaning.

grammar:

try:
    ...(可能产生异常的代码)
except:
    ...(产生异常后的处理代码)

However, there will be a situation, regardless of the above code has no error, we always want to have part of the code is capable of performing, then, we can add another keyword finally.

It can be seen from the literal meaning, the meaning is the last to be executed.

grammar:

try:
    ...(可能产生异常的代码)
except:
    ...(产生异常后的处理代码)
finally:
    ...(一定要执行的代码)

The following code demonstrates we begin today.

Let's develop a scene, we define a division function, if the divisor is not 0, the return value is normal, if the divisor is zero, then the entire program will certainly be an exception error directly.

def division(x, y):
    try:
        return x / y
    except:
        print('程序报错啦!!!')
        return None

print(division(15, 5))

Output:

3.0

At this time the program is normal output, then we modify parameters of the call, instead division(15, 0), look at the output:

程序报错啦!!!
None

We can see, here I print the settings in the program None, red exception information before and did not throw. Here exceptcaptures all of our exception information, but also a lot of anomalies classification, key exceptions such as we faced before the visit does not exist in the dictionary KeyError, such as we have just captured ZeroDivisionErroran exception, there is before us I met the array index out of bounds exception IndexError.

For example, here's the code I can capture more detailed exception ZeroDivisionError.

def division1(x, y):
    try:
        return x / y
    except ZeroDivisionError:
        print('程序报错啦!!!')
        return None

print(division1(15, 0))

Output:

程序报错啦!!!
None

Well, see here, you might have a question, why should we classify abnormal, directly grab all the exceptions than the more convenient it?

Of course, the logic is relatively simple procedure, direct catch all exceptions is more convenient, but in certain business scenarios, a program may throw a variety of exceptions, we hope depending on the type of abnormality, customize different solutions program, at least we know that the current program is to throw the exception, then the program malfunction classification is particularly important.

Here we show you, if we output value is not a number, a string of words. . . .

def division2(x, y):
    try:
        return x / y
    except ZeroDivisionError:
        print('您输出的除数为 0 !!!')
        return None
    except TypeError:
        print('您输出的参数类型非法!!!')
        return None

print(division2('python', 0))

Output:

您输出的参数类型非法!!!
None

Right, you read right, exception information is able to capture more of, is written side by side. As the first throw, it is necessary to see that the anomaly occurs first.

The sample code because the logic is too simple, the order can not be an exception is thrown demonstration, the students please forgive me (li zhi qi zhuang).

We also mentioned above finally, we went on to demonstrate finallythe use of the keyword.

def division3(x, y):
    try:
        return x / y
    except ZeroDivisionError:
        print('您输出的除数为 0 !!!')
        return None
    except TypeError:
        print('您输出的参数类型非法!!!')
        return None
    finally:
        print('你一定能看到我!!!')

print(division3(15, 3))
print(division3('python', 0))

I can see that I use here are abnormal and normal without any problems of data test results are as follows:

你一定能看到我!!!
5.0
您输出的参数类型非法!!!
你一定能看到我!!!
None

Indeed, finallythe content is normally printed, where any more a, where use is often close to some I / O read and write operations or some external connections, such as a database, the cache service.

Today's content on here, dear students, please go back and try on their own.

Sample Code

This series of small series all the code will be placed on code management repository Github and Gitee, to facilitate access.

Sample Code -Github

Sample Code -Gitee

Guess you like

Origin www.cnblogs.com/babycomeon/p/11839613.html