Exception Handling in Python (final)
Exception Handling in Python (final)
Exceptions
An exception is a program event that occurs during program execution and disrupts the flow
of a program. When a Python program cannot cope with a situation, it raises an exception. An
exception is a Python object that represents an error.
The process of catching and preventing unexpected errors during runtime is called exception
handling. It is a mechanism to overrule the exceptions using some blocks.
Built-in exceptions
The exceptions already defined by python are known as built-in exceptions. Python standard
library consists of large number of built-in exceptions. They are as follows:
Exception Explanation
IOError It is raised when the file specified in a program statement cannot be opened.
KeyboardInterrupt It is raised when the user accidentally presses delete or esc key or cancels the execution.
ImportError It is raised when the specified module is not installed or not working.
EOFError It is raised when the end of file condition is reached without reading any data by input().
TypeError It is raised when an operator is supplied with a value of incorrect data type.
It is raised when the result of a calculation exceeds the maximum limit for numeric
OverFlowError
data type.
User-defined exceptions
The exception created by the programmer according to the requirement of the program is
called user-defined exceptions.
1. raise statement
2. assert statement
1. raise statement
It is used to throw an exception. The syntax is as follows:
The optional argument is a string passed to the exception, that displays the message. The
exception may be user-defined or built-in.
Example:
d={'A':9,'B':10}
k=input("Enter key to search:")
if k in d.keys():
print("Key found in dict...")
else:
raise KeyError("Key not present in dict...")
Output:
2. assert statement
An assert statement in Python is used to check a condition in the program code. If the result
after evaluation is false, then the exception is raised.
This statement is generally used at the beginning of the function or after a function call to
check for valid input. The syntax for the assert statement is:
assert Expression[,arguments]
def odd_even(n):
assert (n%2==0),"Even Number..."
print("Odd Number")
odd_even(6)
odd_even(5)
Output:
Step 1: The exception object is created by a Python interpreter that contains information
related to the error such as type, file name, and position where an error has occurred.
Step 2: The object is handed over to the runtime system to find an appropriate code to handle
exceptions. This process is called throwing an exception.
Step 3: The runtime system searches for a block of code known as an exception handler that
handles the raised error. First, it searches for the method by which the error has occurred. If
not found, then it searches the method from which this method is called. This process
continues till the exception handler is found. When a handler is found, it will be executed. This
process is known as catching an exception.
Catching Exceptions
Catching exceptions refers to the execution of code that handles particular exceptions. Any
exception caught through try block can be handled through except block.
try and except block
The try block contains the actual codes that need to be executed. Every try block is followed
by except block. The exception handling code is written inside the except block.
In the execution of the program, if an exception is raised the try block execution is stopped
and the control is shifted to except block. The syntax of try and except is as follows:
try:
program statement in which exception may occur
except [exception_name]:
exception handler code
Output:
Output:
Example 3: ImportError
try:
import Datetime
print("Module")
except ImportError:
print("Invalid module Can't import")
Example 4: ZeroDivisionError
try:
c=5/0
except ZeroDivisionError:
print("You cannot divide")
Example 5: IndexError
l=[11,45,67,89]
try:
print(l[5])
except IndexError:
print("Index not found")
Example 6: TypeError
try:
a=5
print(a+'b')
except TypeError:
print("Invalid Datatypes")
We can also raise exceptions without exception names in except block. Example:
try:
result = 10 / 0
result = 10 +'d'
except ZeroDivisionError, TypeError as e:
print("Error occurred:", e)
In the above code, the ZeroDivisionError exception is raised in the first line, and the relevant
message is generated. If the first exception is not raised then it will jump to another exception
i.e. TypeError.
2. Writing multiple exception handlers with separate except blocks
Multiple except blocks are required for this method. Example:
try:
result = 10 / 0
result = 10 + 'd'
except ZeroDivisionError as e:
print("Error occurred:", e)
except TypeError as e1:
print("Error occurred:",e1)
a=15
b=10
c=a-b
print("Value of c=",c)
Output:
The else block in exception handling in Python will be executed in a similar manner as it is
executed in if…else, while..else etc. Example:
Output:
If sometimes any exception which is not caught in exception handler, in this scenario too the
finally clause will execute first and the exception is re-raised. Example:
Output:
After execution of finally block, Python transfers the control to a previously entered try or to
the next higher level default exception handler. In such a case, the statements following the
finally block is executed. That is, unlike except, execution of the finally clause does not
terminate the exception. Rather, the exception continues to be raised after execution of finally.