Exception Handling

Try-Except Block#

try:
doSmth()
except OSError as err:
print("OS Error: {0}".format(err))
except ValueError:
print("Could not convert data")
except:
print("Unexpected error!")
raise

Raising Exceptions#

if x > 0:
raise RuntimeError("Input cannot be greater than zero.")
else:
doSmth();

Creating Your Own Exceptions#

class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
# Main Program
if x > 0:
raise ValueTooLargeError

Reference: https://docs.python.org/3/tutorial/errors.html