There are 3 possible "states": never occurred
, handled
and unhandled
.
You can map the control flow of the try-catch-else-finally clause into these 3 states like that:
from traceback import print_last
e_state = 'unhandled exception'
try:
# cause an exception here [or don't]
except SomeException as e: # use a suitable [or not] exception type here
e_state = 'handled exception'
print('in "except"')
else:
e_state = 'no exception'
print('in "else"')
finally:
print(f'in "finally". {e_state} occurred')
if e_state == 'handled exception':
print_last() # since the exception was caught - explicitly inform about it
Full examples below:
1. Handled Exception
from traceback import print_last
e_state = 'unhandled exception'
try:
1 / 0
except ZeroDivisionError as e:
e_state = 'handled exception'
print('in "except"')
else:
e_state = 'no exception'
print('in "else"')
finally:
print(f'in "finally". {e_state} occurred')
if e_state == 'handled exception':
print_last()
Output:
in "except"
in "finally". handled exception occurred
Traceback (most recent call last):
File "...IPython/core/interactiveshell.py", line 3251, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File ".../T/ipykernel_59815/1316012763.py", line 5, in <module>
1 / 0
ZeroDivisionError: division by zero
2. Unhandled Exception
from traceback import print_last
e_state = 'unhandled exception'
try:
1 / 0
except KeyError as e:
e_state = 'handled exception'
print('in "except"')
else:
e_state = 'no exception'
print('in "else"')
finally:
print(f'in "finally". {e_state} occurred')
if e_state == 'handled exception':
print_last()
Output:
in "finally". unhandled exception occurred
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Input In [14], in <module>
3 e_state = 'unhandled exception'
4 try:
----> 5 1 / 0
6 except KeyError as e:
7 e_state = 'handled exception'
ZeroDivisionError: division by zero
3. No Exception
from traceback import print_last
e_state = 'unhandled exception'
try:
1 / 2
except ZeroDivisionError as e:
e_state = 'handled exception'
print('in "except"')
else:
e_state = 'no exception'
print('in "else"')
finally:
print(f'in "finally". {e_state} occurred')
if e_state == 'handled exception':
print_last()
Output:
in "else"
in "finally". no exception occurred