A little summary, otherwise always forget.
x = ' abc '
def fetcher (obj, index): Return
Obj[index]
fetcher (x, 4)
Output:
File "test.py", line 6, in <module>
fetcher (x, 4)
file "test.py", line 4, in Fetcher return
obj[index]
indexerror:string index out of range
the 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: No matter whether a try or not an exception, finally always execute
Def catcher ():
try:
fetcher (x, 4)
finally:
print ' after Fecth '
Output:
After Fecth
Traceback (most recent called last):
file "test.py", line <module>
catcher ()
file "test.py", line, in catcher
Fetcher (x, 4)
File "test.py", line 4, in Fetcher return
Obj[index]
IndexEr Ror: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 action: There is no else statement, and when the try statement is executed, it is not known whether an exception has occurred, or an exception has occurred and has been processed. Separated by what else can be clear.
Fourth: Using raise to pass exceptions
Def catcher ():
try:
fetcher (x, 4)
except:
print "got Exception"
raise
Output:
Got exception
Traceback (most recent call last):
File "test.py", line Notoginseng, in <module>
catcher ()
File "test.py", line, in catcher
Fetcher (x, 4)
File "test.py", line 4, in Fetcher return
Obj[index]
Indexerror:string index out of range
When the raise statement does not include an exception name or additional data, the current exception is raised again. If you want to catch a handle to an exception, and you don't want to
The exception disappears in the program code and can be raise again by using the.
Fifth: Except (name1, name2)
Def catcher ():
try:
fetcher (x, 4)
except (TypeError, indexerror):
print "got Exception"
else:
print "not exception"
Captures the exceptions listed in the list for processing. If there are no arguments after except, all exceptions are caught.
Def catcher ():
try:
fetcher (x, 4)
except:
print "got Exception"