I am not sure why we need finally
in try...except...finally
statements. In my opinion, this code block
JavaScript
x
6
1
try:
2
run_code1()
3
except TypeError:
4
run_code2()
5
other_code()
6
is the same with this one using finally
:
JavaScript
1
7
1
try:
2
run_code1()
3
except TypeError:
4
run_code2()
5
finally:
6
other_code()
7
Am I missing something?
Advertisement
Answer
It makes a difference if you return early:
JavaScript
1
8
1
try:
2
run_code1()
3
except TypeError:
4
run_code2()
5
return None # The finally block is run before the method returns
6
finally:
7
other_code()
8
Compare to this:
JavaScript
1
8
1
try:
2
run_code1()
3
except TypeError:
4
run_code2()
5
return None
6
7
other_code() # This doesn't get run if there's an exception.
8
Other situations that can cause differences:
- If an exception is thrown inside the except block.
- If an exception is thrown in
run_code1()
but it’s not aTypeError
. - Other control flow statements such as
continue
andbreak
statements.