part7-2 Python exception processing (abnormal propagation track, the traceback module, exception handling rules), exception handling exercises


A, Python exception propagation trace

exception object has a track with_traceback offer spread for handling exceptions, see the source of anomalous propagation trace anomaly traceable trigger can also be seen all the way to trigger abnormaltrajectory. Examples are as follows:
. 1  class SelfException (Exception): Pass 
2  
. 3  DEF main ():
 . 4      firstMethod ()
 . 5  DEF firstMethod ():
 . 6      secondMethod ()
 . 7  DEF secondMethod ():
 . 8      thirdMethod ()
 . 9  DEF thirdMethod ():
 10      The raise SelfException ( " custom exception information " )
 . 11  main ()
 12 is  
13 is  output as follows:
 14  Traceback (MOST Recent Last Call):
 15    File " traceback_test.py ", line 15, in <module>
16     main()
17   File "traceback_test.py", line 8, in main
18     firstMethod()
19   File "traceback_test.py", line 10, in firstMethod
20     secondMethod()
21   File "traceback_test.py", line 12, in secondMethod
22     thirdMethod()
23   File "traceback_test.py", line 14, inthirdMethod
 24      The raise SelfException ( " custom exception information " )
 25  __main__ .SelfException: Custom abnormality information
From the above output () function to start trigger an exception from thirdMethod, spread secondMethod () function, and then spread firstMethod () function, and eventually reached the main () function () function terminates the main, this process is the Python exception spread trajectory. 

Actual development, complicated operations are divided into a series function or method call. Because in order to have better reusability, reusable code will each unit defined as a function or method, the gradual decomposition of complex tasks for the small sub-tasks more manageable. Usually a large business function needs to be jointly carried out by more than one function or method, in the final programming model, many objects will be achieved communication, through a series of tasks to perform a function or method call.

A series of function or method call occurs when a program is running, forming a "function call stack." Abnormal propagation is the opposite: the exception is not fully captured long (including the exception is not caught, or the exception is re-initiated after a new exception handling), abnormal spread gradually outwardly from the abnormal function or method, first of all passed to the function or method caller, the function or method of the caller and then pass it to the last caller ······ Python interpreter reached, then abort the Python interpreter program, and print information abnormal propagation trace.

In the output above information, there have been many mistakes, but actually only a mistake, multi-line information system prompt is displayed in turn triggered abnormal trajectory. The above output information recording various points in the program execution is stopped. The last row shows the detailed exception message type and exceptions. From one line up, one by one record the source of an exception occurs, the exception in order to propagate through the track, and indicate an abnormality occurs in which file, which line, which function at.

Python traceback module is dedicated to providing the processing exception propagation track, traceback module provides two common methods :
(1), traceback.print_exc (): the output is abnormal propagation trace information to the console or the specified file.
(2), format_exe (): converts a string exception propagation path information.

Omitted print_exc () method, the two parameters limit, file, together with formal parameters are: print_exc ([limit [, file ]]), but this form of complete form print_exception (etype, value, tb [ , limit [, File]]), in the complete form, the first three parameters are used to specify the following information abnormality:
(. 1), the etype: Specifies the type of exception.
(2), value: value specified exception.
(3), tb: Specifies the traceback information about the exception.

Except when the program in a block, the block except the abnormality information captured objects can be obtained by sys, wherein sys.exc_type, sys.exc_value, in sys.exc_traceback or on behalf of the current exception except block type, the outliers and abnormal propagation trajectory. At this time print_exc ([limit [, file] ]) corresponding to the following form:
print_exception (sys.exc_type, sys.exc_value, sys.exc_tb [, limit [, File]])

is used print_exc ([limit [, file] ]) will automatically process the current exception except block captured. The method involves two parameters are:

(. 1), limit: displaying the number of layers for limiting abnormal propagation of, for example function A calls function B, function B abnormality occurs, if the specified limit = 1, only the display function AInside the exception. Do not set the limit argument, the default display all.
(2), file: Specifies the output abnormal propagation path information to the specified file. This parameter is not specified, then the output to the console.

Means traceback module can be used to capture exception except block, and in which abnormal propagation print information, including outputs it to a file. Examples are as follows:
. 1  Import traceback         # introduced traceback module 
2  class SelfException (Exception): Pass 
. 3  
. 4  DEF main ():
 . 5      firstMethod ()
 . 6  DEF firstMethod ():
 . 7      secondMethod ()
 . 8  DEF secondMethod ():
 . 9      thirdMethod ()
 10  DEF thirdMethod ( ):
 . 11      The raise SelfException ( " custom exception information " )
 12 is  the try :
 13 is      main ()
 14  the except :
 15     # Capture abnormal, abnormality and dissemination of information to the console 
16      traceback.print_exc ()
 . 17      # capture exception, the exception is propagated to the specified information file 
18 is      traceback.print_exc (= File Open ( ' log.txt ' , ' A ' ))
The above code traceback module is first introduced, followed except the use of exception capture process, and uses print_exc traceback () method outputs an abnormal dissemination of information, respectively, and outputs it to the console specified in the specified file. Running the above code can be seen in abnormal propagation information output from the console, and the directory where the files to generate a log.txt file, the file also record the abnormality information dissemination. 

Second, the rule exception handling

successful exception handling should achieve the following four objectives:
(1) the program code to minimize confusion.
(2) capture and retain diagnostic information.
(3) to notify appropriate personnel.
(4) using suitable means end abnormal activity.

1, do not overuse abnormal
abuse disorders mechanism would have a negative impact, excessive use exceptions reflected in two aspects:
(1), the abnormal and confused with common error, no longer write any error handling code, but a simple an exception is thrown instead of all the error handling.
(2), instead of using the exception handling control flow.

For the known bugs and common errors should be prepared to deal with this error code, increasing the robustness of the program. Only for external runtime error can not be determined and predictable used only exception. For example, in backgammon game, the process in two ways a user input coordinate point existing pieces of:
# If the chess point is not empty (there chess pieces) 
IF Board [int (y_str) - 1] [int (x_str) - 1] =! " " : 
    inputstr = the INPUT ( " coordinate input point you have pawn, please re-enter \ the n- " )
     the Continue
This approach is simple and clear, logical, process efficiency is also very good, if the program proceeds to block, i.e., the end of this cycle. If the above process mode to the following form:
# If you want to play chess point is not empty (there chess pieces) 
IF Board [int (y_str) - 1] [int (x_str) - 1] =! " " :
     # trigger default RuntimeError abnormal 
    raise
This approach does not provide effective error handling code is detected coordinate points have chess pieces, no corresponding processing, simply raise an exception. This approach is simple, but the Python interpreter receives this exception, into the respective required except block catches the exception, so the operating efficiency to be worse, and board games repeating this error completely predictable, so the program can provide appropriate treatment for this error, instead of raising it. 

It is noted that : exception handling mechanism intention is to exception handling code and normal business logic processing code separation is not expected, and therefore should never be used in place of the normal exception handling business logic judgment. Further, the difference in the efficiency of exception mechanism efficiency than the normal flow control, so do not use the exception handling instead of normal program flow control.

2, try not to use too large a block of
code in the try block is too large can cause abnormal greatly increase the likelihood of the emergence of the try block, resulting in difficulty of analysis of error factors also increased significantly. When very large try block, behind requires a large number of blocks available for different except different exception handling logic to provide, in a large number of the same except block after a try block needs to analyze the logical relationships between them, but increase the complexity of programming .

Therefore, a large block may try the program section into a plurality of possible abnormal, and in a separate try block, respectively, so that the capture and handle exceptions.

3, do not ignore caught exception
when an abnormality occurs in the except block should do something useful, such as processing and repair abnormal, except block can not be set to empty or simply print exception information. Abnormal take appropriate measures, such as:
(1), handle exceptions. Suitable repair an abnormal state, and where the exception occurred and continue the bypass; or other data calculated using, instead of the method to return the desired value; orThe user is prompted to re-operation, etc. In short, the program should try to repair abnormal, the program can resume operation.
(2) to re-trigger a new exception. To do as much as possible under the current operating environment things done, and then translated abnormal, the abnormal abnormal packed into the current layer, re-upload to the upper caller.
(3) in an appropriate exception handling layer. If the current layer is not clear how to handle exceptions, do not use the current layer except statement to catch the exception, so that upper caller to be responsible for handling the exception.

Third, abnormal nodules

1, Python exception handling depends try, except, else, finally and raise five keywords, as well as the five key usage.
2, abnormal inheritance relationship between classes.
3, abnormal capture detailed processing method, and how to use lead to raise a custom exception based on business needs.
4, the actual use common exception handling, exception handling, and a few ground rules.

Exercise:

1, prompt for an integer N, N represents the next string of numbers can be entered, each string separated by a space, each program number string into two spaces divided by an integer, and calculates the two integers the results divisible. Use exception handling mechanism to handle various error conditions entered by the user and prompts the user to re-enter.
str_N = input("请输入整数N:")
try:
    n = int(str_N)
    print(n)
    i = 0
    try:
        while True:
            a, b = input("请输入2个整数(空格分隔):").split()
            print(int(a) // int(b))
            i += 1
            if i >= n: break
    except:
        print("必须输入2个空格隔开的整数!")
except:
    print("请输入整数N!")

2、提示输入一个整数,如果输入的整数是奇数,则输出“有趣”;如果输入的整数是偶数,且在2~5之间,则输出“没意思”;如果输入的整数是偶数,且在 6~20 之间,则输出“有趣”;如果输入的是整数是其他偶数,则打印“没意思”。要求使用异常处理机制来处理用户输入的各种错误情况。
while True:
    str_n = input("请输入一个整数:")
    if str_n == 'q':
        import sys
        sys.exit(0)
    try:
        n = int(str_n)
        if n % 2 != 0:
            print("有趣")
        elif 5 >= n >= 2:
            print("没意思")
        elif 20 >= n >= 6:
            print("有趣")
        else:
            print("没意思")
    except:
        print("请按照要求输入一个整数!")

3、提供一个字符串元组,程序要求元组中每一个元素的长度都在 5~20 之间;否则,程序引发异常。
class LengthError(Exception): pass
def foo(tp):
    for s in tp:
        if not isinstance(s, str):
            raise ValueError("所有元素必须是字符串")
        if not (20 >= len(s) >= 5):
            raise LengthError("字符串长度要求在5~20之间!")
    print(tp)

if __name__ == '__main__':
    str_tuple = ('python', 'linuxb', 'michael', 'this', 'java')
    foo(str_tuple)

4、提示输入 x1, y1, x2, y2, x3, y3 六个数值,分别代表三个点的坐标,程序判断这三个点是否在同一条直线上。要求使用异常处理机制处理用户输入的各种错误情况,如果三个点不在同一条直线上,则程序出现异常。
while True:
    st = input("请输入3个点的x、y值,以空格分隔:")
    if st == 'q':
        import sys
        sys.exit(0)
    try:
        x1s, y1s, x2s, y2s, x3s, y3s = st.split()
        x1, y1, x2, y2, x3, y3 = float(x1s), float(y1s), float(x2s), float(y2s), float(x3s), float(y3s)
        if x1 == 0 and x2 ==0 and x3 == 0:
            print("在同一条直线上!")
        elif 0 in (x1, x2, x3):
            print("不在同一条直线上")
        elif y1 / x1 == y2 / x2 and y1 / x1 == y3 / x3:
            print("在同一条直线上!")
        else:
            print("不在同一条直线上!")
    except:
        print("必须输入6个空格隔开的整数!")

 

Guess you like

Origin www.cnblogs.com/Micro0623/p/11810629.html