Illustrate the use of try/except/finally.
If you do not use try/except/finally
1 ' ABC ' 2 def fetcher (obj, index): 3 return Obj[index] 4 5 fetcher (x, 4)
Output:
" test.py " in <module> 4) "test.py" in fetcher return obj[index]indexerror:string Index out of range
Using try/except/finally:
First: Try not only catches exceptions, but also resumes execution
1 def catcher (): 2 Try : 3 Fetcher (x, 4)4 except:5 print" got exception"6 print"continuing "
Output:
Got Exceptioncontinuing
Second: The finally will execute regardless of whether or not the try has an exception
1 def catcher (): 2 Try : 3 Fetcher (x, 4)4 finally:5 print 'afterfecth'
Output: (There is no except, that is, there is no way to deal with the exception, the default way to treat the exception as Python, the program will stop)
After Fecthtraceback (most recent call last): " test.py " in <module> catcher () "test.py" in catcher 4) "test.py" in fetcher return obj[index]indexerror:string Index out of range
Third: Try no exception to execute else
There is an abnormal situation.
1 defcatcher ():2 Try:3Fetcher (x, 4)4 except:5 Print "got exception"6 Else:7 Print "Not exception"
Output:
Got exception
No abnormal situation:
1 defcatcher ():2 Try:3Fetcher (x, 2)4 except:5 Print "got exception"6 Else:7 Print "Not exception"
Output:
Not exception
Else: There is no else statement, and when the try statement is executed, there is no way to know whether an exception has occurred or an exception has occurred and has been processed. Can be clearly separated by else.
IV: Using raise to transfer anomalies
1 def catcher (): 2 Try : 3 Fetcher (x, 4)4 except:5 print" got exception"6 raise
Output:
got Exceptiontraceback (most recent call last): File " test.py " , line Notoginseng, in <module> catcher () File " test.py ", line, in catcher Fetcher (X, 4) File Span style= "color: #800000;" > " test.py " , line 4, in Fetcher return Obj[index]indexerror:string index out of range
When the raise statement does not include the exception name or additional data, the current exception is re-thrown (that is, an exception has occurred before entering except). If you want the catch to handle an exception and you do not want the exception to disappear in the program code, you can re-throw the exception through raise.
V: Except (name1, name2)
1 defcatcher ():2 Try:3Fetcher (x, 4)4 except(TypeError, indexerror):5 Print "got exception"6 Else:7 Print "Not exception"
Captures the list of exceptions that are listed for processing. If there are no arguments after except, all exceptions are caught.
1 def catcher (): 2 Try : 3 Fetcher (x, 4)4 except:5 print" got exception"
Python try/except/finally