An exception is an event that occurs during the program execution. In this example we will show how to handle exceptions in Python.
2. Exception Handler
- Use the try/except/else statement to catch exceptions.
- After exception is captured in the try block, the except statement will process it.
- else statement will be executed when there is no exception found in try clause.
try:
<statement>
except <name>:
<statement>
except <name>,<data>:
<statement>
else:
<statement>
For multiple except statements, Python executes the first exception clause that matches the exception type. After the exception is processed, the control flow passes through the entire try statement (unless new exceptions are raised when the exception is handled).
Source Code
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
def main():
try:
sum1 = 1 + '1' # TypeError
except TypeError as reason:
print('Data type error', 'nthe reason is :', str(reason))
if __name__=='__main__':
main()
We can obtain the results as follows:
Data type error
the reason is : unsupported operand type(s) for +: 'int' and 'str'