Exception Handling in Python
Exceptions are errors that generates unexpected output or behaves abnormally.
Built-in Exceptions
Commonly occurring exceptions are usually defined in the compiler/interpreter. These are
called built-in exceptions.
Built-in exceptions in Python
S. No Name of the Explanation
Built-in
Exception
1. SyntaxError It is raised when there is an error in the syntax of
the Python code.
2. ValueError It is raised when a built-in method or operation
receives an argument that has the right data type but
mismatched or inappropriate values.
3. IOError It is raised when the file specified in a program
statement cannot be opened.
4 KeyboardInterrupt It is raised when the user by mistake hits the
Delete or Esc key while executing a program due
to which the normal flow of the program is interrupted.
5 ImportError It is raised when the requested module definition is not
found.
6 EOFError It is raised when the end of file condition is reached
without reading any data by input().
7 ZeroDivisionErro It is raised when the denominator in a division operation
r is zero.
8 IndexError It is raised when the index or subscript in a sequence is
out of range.
9 NameError It is raised when a local or global variable name is not
defined.
10 IndentationError It is raised due to incorrect indentation in the program
code.
11 TypeError It is raised when an operator is supplied with a value of
incorrect data type.
12 OverFlowError It is raised when the result of a calculation exceeds the
maximum limit for numeric data type.
Program of Exception handling in python
try:
a= int(input("Enter a number: "))
b=int(input("Enter other number: "))
c=a/b
print("Division performed successfully.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
except ValueError:
print("Only integer values are allowed")
except:
print("Some exception raised")
else:
print("Division of two number is: ", c)
finally:
print("Over and Out")
Output:
Enter a number: 58
Enter other number: xyz
Only integer values are allowed.
Over and Out
=== Code Execution Successful ===
Enter a number: 857
Enter other number: 0
Division by zero is not allowed.
Over and Out
=== Code Execution Successful ===
Need for Exception Handling
It is a useful technique that helps in capturing runtime errors and handling them so as to avoid
the program getting crashed.
try block
Exceptions, if any, are caught in the try block
except block
Exceptions, if any, are handled in the except block
Else block
If there is no error then none of the except blocks will be executed. In this case, the
statements inside the else clause will be executed.
finally block
The statements inside the finally block are always executed whether an exception has
occurred in the try block or not.