[code block]
- x = ' abc '
- def fetcher (obj, index):
- return Obj[index]
- Fetcher (x, 4)
Output:
- File "test.py", line 6, <module>
- Fetcher (x, 4)
- File "test.py", line 4, in Fetcher
- return Obj[index]
- Indexerror:string index out of range
First: Try not only catches exceptions, but also resumes execution
- Def catcher ():
- Try:
- Fetcher (x, 4)
- except:
- print "Got exception"
- print "continuing"
Output:
- Got exception
- Continuing
Second: The finally will execute regardless of whether or not the try has an exception
- Def catcher ():
- Try:
- Fetcher (x, 4)
- finally:
- print ' after Fecth '
Output:
- After FECTH
- Traceback (most recent):
- File "test.py", line-in <module>
- Catcher ()
- File "test.py", line catcher
- Fetcher (x, 4)
- File "test.py", line 4, in Fetcher
- return Obj[index]
- Indexerror:string index out of range
Third: Try no exception to execute else
- Def catcher ():
- Try:
- Fetcher (x, 4)
- except:
- print "Got exception"
- Else:
- Print "not exception"
Output:
- Got exception
- Def catcher ():
- Try:
- Fetcher (x, 2)
- except:
- print "Got exception"
- Else:
- 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
- Def catcher ():
- Try:
- Fetcher (x, 4)
- except:
- print "Got exception"
- Raise
Output:
- Got exception
- Traceback (most recent):
- File "test.py", line Notoginseng, in <module>
- Catcher ()
- File "test.py", line A, in catcher
- Fetcher (x, 4)
- File "test.py", line 4, in Fetcher
- return Obj[index]
- Indexerror:string index out of range
The current exception is re-thrown when the raise statement does not include the exception name or additional information. If you want the capture to handle an exception, and you do not want
The exception disappears in the program code and can be re-thrown by raise.
V: Except (name1, name2)
- Def catcher ():
- Try:
- Fetcher (x, 4)
- except (TypeError, indexerror):
- print "Got exception"
- Else:
- Print "not exception"
Captures the list of exceptions that are listed for processing. If there are no arguments after except, all exceptions are caught.
- Def catcher ():
- Try:
- Fetcher (x, 4)
- except:
Python try/except/finally, etc.