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')
start
1
4
end
print('start')を
最初に実行。
次に、
tryブロックを実行する。
tryブロック1行目のtest_exception関数に引数1で入る。
なので、
print(1)を実行し、
answer = 100
となり100を返す。
retrunしているので、
その下のprint(2)は実行されない点に注意。
tryブロックのtest_exception関数が終わったので、
その続きでprint(4)を実行。
ZeroDivisionErrorは発生していないので、
exceptブロックは実行せず、とばす。
最後にfinallyブロックを実行する。
test_exception関数の引数を0にすると、
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')
start
1
3
division by zero
end
print('start')を
最初に実行。
次に、
tryブロックを実行する。
tryブロック1行目のtest_exception関数に引数0で入る。
なので、
print(1)を実行し、
answerが100を0で割る事になりエラー発生。
この場合も、
retrunしているので、
その下のprint(2)は実行されない点に注意。
tryブロックのtest_exception関数でエラーが発生した為、
その続きは実行されない。
ZeroDivisionErrorが発生しているので、
exceptブロックを実行する。
最後にfinallyブロックを実行する。