1
def test_exception(num):
print(1)
answer = 100 / num
return answer
print(2)
print('start')
try:
test_exception(1)
print(4)
except ZeroDivisionError as e:
print(3)
print(e)
finally:
print('end')
Execution result of 1
start
1
4
end
print ('start') Run first.
next, Execute a try block. Enter the test_exception function on the first line of the try block with argument 1. So Execute print (1) and answer = 100 And returns 100. Because it is returning Note that print (2) below it is not executed. Now that the test_exception function of the try block is finished Then execute print (4).
Since ZeroDivisionError has not occurred The except block is not executed and is skipped.
Finally, execute the finally block.
If the argument of the test_exception function is 0,
2
def test_exception(num):
print(1)
answer = 100 / num
return answer
print(2)
print('start')
try:
test_exception(0)
print(4)
except ZeroDivisionError as e:
print(3)
print(e)
finally:
print('end')
Execution result of 2
start
1
3
division by zero
end
print ('start') Run first.
next, Execute a try block. Enter the test_exception function on the first line of the try block with 0 arguments. So Execute print (1) and An error occurs because the answer divides 100 by 0. Again, Because it is returning Note that print (2) below it is not executed. An error occurred in the test_exception function of the try block, so The continuation is not executed.
Since ZeroDivisionError has occurred Execute the except block.
Finally, execute the finally block.
Recommended Posts