Nested exception Handlers
In fact, we need to figure out the main problem should be that, when the exception occurs, whether it is simple exception handling or complex exception handling, we should be able to clearly understand where the abnormal run to, who captured, and now control to where the right, Let's analyze the example of nested exception handling to illustrate the above mentioned problems.
Here are the try/except and try/finally for exception handling when an exception occurs:
Below we will use the program to see what happens when an exception occurs:
cases where nested try/except are used:
defAction2 ():Print(1+[])#TypeErrorTry: Try: Action2 ()Print('Inner Try') exceptTypeError:Print('Inner except') Print('Outer try')exceptTypeError:Print('Outter except')
The operation results are as follows
Excepttry
Our main purpose is to understand where the control of the situation is: When Action2 raises a typeerror, the information behind the inside Try/excpt's try module does not continue to execute, instead of the except information, when except captures this information, Execute the information inside the except, and then this time the control of the program to go outside the try/except, and then outside the try/except because there is no exception, so do not execute except inside the code, the program continues to go outside the try/except
How the try/finally is executed
Try: Try: RaiseIndexerrorPrint('Inner Try') finally: Print('Inner finally') Print('Outer try')finally: Print('Outer finally')
The following results are performed:
FinallyfinallyTraceback (most recent call last): "D:\application\ eclipse\workspace\yichang\c4\t3.py" in <module> raise Indexerrorindexerror
Note When using try/finally, when an error occurs in a try, the code will continue to be thrown up, no error is captured, and eventually thrown to the top level by the default exception handler.
try/excpet/finally The code for nesting time:
defRaise1 ():RaiseIndexerrordefRaise2 ():returndefRAISE3 ():RaiseTypeError forFuncinch(RAISE1,RAISE2,RAISE3):Try: Print('Inner Try') Try: func ()exceptIndexerror:Print('Inner except') Print('Outer try') finally: Print('Outer finally') Print('\ n')
The results of the operation are as follows:
InnerTryInnerexceptouterTryouterfinallyInnerTryouterTryouterfinallyInnerTryouterfinallyTraceback (most recent): File"D:\application\eclipse\workspace\yichang\c4\t4.py", Line 9,inch<module>func () File"D:\application\eclipse\workspace\yichang\c4\t4.py", Line 3,inchRAISE3defRAISE3 ():RaiseTypeerrortypeerror
the customary usage of exceptions
1: Exception is not always error
Errors are always abnormal, and exceptions are not always errors. In fact, in the process of running the program, we need an exception to match our program to continue to run. Some of the anomalies are just signals, such as Eoferror and Systemexit and keyboardinterrupt anomalies.
2: Close file and server connections
including databases and other connections, in fact, there is a closed connection process, this time using try/finally. Now, we have a new option, which is to use With/as.
3:sys.exc_info
When using the empty except, can be used in conjunction with sys.exc_info to output some useful information, when the processor processing, Sys_exc_info will have (type,value,traceback) information, The (none,none,none) message is returned when there is no processor processing error.
skills related to exceptions
1: What exception should be packaged
In fact, mainly about our attitude towards the abnormal, do not we learn the exception, we run any code to add exception handling, this will make us look frightened. Sometimes we do not need to do the exception capture, because the program run error is actually what we need, we can modify these errors. We are mainly caught in a place where we feel that we often fail. Try/finally are used in places where they need to be closed. It is better to use exceptions outside of a single function than to use multiple exceptions within them.
2: Too many captures
When we use a excpet, we can catch all the exceptions, so the program looks unusually concise, you can safely run your code, but this is not very good, we should be able to capture as accurately as possible the errors we need, otherwise, Except will intercept the error that our program does not appear, analyze the following example:
Mydic = {1:'a', 2:'b'}try: = Mydic[3]except: = Noneprint(x)
In fact, the original meaning of our code is this, when we appear keyerror, our x value is none. If our dictionary name is wrong, we want to throw an exception or do something different, but this time, our code will also let the value of x is None.
3: Too few snaps
One problem with capturing too little is that when we modify the program, we need to add our exceptions to the except, so we can use a high level exception to deal with this change.
The design of the 35th chapter of the Python Learning Handbook