Exception passing
1. Try is nested
import time
try:
f = open('test.txt')
try:
while True:
content = f.readline()
if len(content) == 0:
break
time.sleep(2)
print(content)
finally:
f.close()
print('Close file')
except:
print("There is no such file.")
Copy the code
Running results:
In [26] :importtime ... :try:
...: f = open('test.txt')
...: try:
...: while True:... : content = f.readline() ... :if len(content) == 0:
...: break. : time.sleep(2)
...: print(content) ... :finally:... : f.close() ... :print('Close file')
...: except:
...: print("There is no such file.")
...: finally:
...: print("Finally")... : XXXXXXX --> This is the last of the test.txt files that read the information ^C close file without this filefinally
Copy the code
2. Nested function calls
def test1() :
print("----test1-1----")
print(num)
print("----test1-2----")
def test2() :
print("----test2-1----")
test1()
print("----test2-2----")
def test3() :
try:
print("----test3-1----")
test1()
print("----test3-2----")
except Exception as result:
print("Exception caught, message :%s"%result)
print("----test3-2----")
test3()
print("------ gorgeous dividing line -----")
test2()
Copy the code
Running results:
Conclusion:
- If the inner try does not catch the exception, the outer try will receive the exception and process it. If the outer try still does not catch the exception, the outer try will pass it.
- If an exception is generated in A function, such as function A — — — — — — — — > B > function function C, and exception is in the function of C, so if A function in C not to deal with this exception, so this exception will be passed to the function of B, if you have any exception handling function B will be carried out in accordance with the function B’s handling of execution; If function B also has no exception handling, the exception is passed on, and so on… If none of the functions are handled, then the exception is handled by default, which is what you normally see
- Notice in the figure above, when test3 is called, an exception is raised inside test1. This exception is passed to test3 to complete the exception processing. When the exception processing is complete, execution is not returned to test1, but continues in test3