Code Examples
Based On:
Python Exception Handling
# generic exception capture
try:
Code That Causes An Exception
except Exception as e:
print(e)
# specific exception capture
try:
Code That Causes An Exception
except ZeroDivisionError:
print('division error')
except IndexError:
print('index error')
# run a block of code if the code
# inside try runs without any errors
try:
Code That Causes An Exception
except Exception as e:
print(e)
else:
Code Block
# the finally block is always executed
# if there is an exception or not
try:
Code That Causes An Exception
except Exception as e:
print(e)
finally:
Code Block
Links
Exception Handling
(Python 3.12.3 Doc)
Built-in Exceptions
(Python 3.12.3 Doc)
User-defined Exceptions in Python with Examples