Python exception handling rules
--try
: Exception handling of enclosed code
--ʻExcept : Block to be executed when an error-case exception occurs --ʻExcept
: Block to execute when any exception occurs
--ʻElse: Block to execute only if no exception occurs --
finally`: Block to execute with or without an exception
Sample code
test_exception.py
import sys
zerodiv = len(sys.argv) > 1
try:
if zerodiv:
a = 10 / 0
else:
a = 10 / 1
print("answer = {}".format(a))
except ZeroDivisionError as e:
print("ZeroDivisionError")
else:
print("else statement")
finally:
print("finally statement")
Execution result
$ python test_exception.py
answer = 10
else statement
finally statement
$ python test_exception.py zerodiv
ZeroDivisionError
finally statement
Recommended Posts