Advanced Usage Python exception handling

Python's basic usage

try:
	<语句块1>
except:
	<语句块2>
except:
	<语句块3>

Python's Advanced Usage

try:
	<语句块1>
except:
	<语句块2>
else:
	<语句块3>
finally:
	<语句块4>

Meaning try-except unchanged advanced use, except can have multiple sets. else if the try bonus when no abnormality <statement block 1>. finally the content that must be executed. This combination of four reserved words you can cope with all situations. Statement abnormality has not occurred, then execution path is 1-> 3-> 4. And vice versa is 1-> 2-> 4

Advanced usage of Python usage in the function of

def f(a):
	try:
		print(1/a)
		rerturn 1/a
	except:
		print("except")
		rerturn "except"
	else:
		print("else")
		rerturn "else"
	finally:
		print("finally")
		rerturn "finally"

At this convention: regardless of return occur in any place, as long as there is finally in exception handling you must want to finally statements to the function returns executed.

>>>f(1)
1.0
fiinally
'finally'
>>>f(0)
except
finally
'finally'

Because there return in the try, even if there is no abnormality, the function will be executed before finally lead to the return of the statement.

Released five original articles · won praise 0 · Views 209

Guess you like

Origin blog.csdn.net/bilidi/article/details/104524668