0% found this document useful (0 votes)
11 views9 pages

Exception Handling in Python (final)

Uploaded by

farhaanzilani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
11 views9 pages

Exception Handling in Python (final)

Uploaded by

farhaanzilani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 9

EXCEPTION HANDLING IN PYTHON

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.

The following terms are used for exception handling:

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

It is raised when a built- in method or operation mismatched or inappropriate values


ValueError
are provided as input.

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().

ZeroDivisionError It is raised when any number is having denominator zero.

IndexError It is raised when the index or subscript in a sequence is out of range.

NameError It is raised when a variable is accessed before declaration.

IndentationError It is raised due to incorrect indentation in the program code.

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.

The user defined-exception can be created using two methods:

1. raise statement
2. assert statement

1. raise statement
It is used to throw an exception. The syntax is as follows:

raise exception-name[(optional argument)]

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]

On encountering an assert statement, Python evaluates the expression given immediately


after the assert keyword. If this expression is false, an AssertionError exception is raised
which can be handled like any other exception.
Example:

def odd_even(n):
assert (n%2==0),"Even Number..."
print("Odd Number")
odd_even(6)
odd_even(5)

Output:

Process of exception handling

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.

Step 4: Finally the program gets terminated

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

Example 1 : NameError Exception


try:
print(x)
except NameError:
print("Variable is not defined...")

Output:

Example 2: ValueError Exception


try:
a = int(input("Enter your age: "))
except ValueError:
#Print message for ValueError
print("Enter numbers only")

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:

print ("Handling multiple exceptions")


try:
a=10 / 0
except:
print("Exception Raised...")

Handling multiple exceptions


Multiple exceptions can be handled together using multiple exceptions with multiple exception
handlers. There are two ways to handle multiple exceptions.

1. Writing multiple exception handlers together


2. Writing multiple exception handlers with separate except blocks

1. Writing multiple exception handlers together


The multiple exception handlers can be written within one except block. When the first
exception is raised it will stop execution and evaluate the first except block. Example:

try:
result = 10 / 0
result = 10 +'d'
except ZeroDivisionError, TypeError as e:
print("Error occurred:", e)

Output: Error occurred: division by zero

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:

Use of else clause in exception handling in


Python
In the process of exception handling, the except block will be executed if any exception is
raised in the try block. But when no error is reported, then no except block will be executed.
In this scenario else block comes into play a role.

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:

print ("Handling multiple exceptions")


try:
n1=int(input("Enter number1:"))
n2=int(input("Enter number2:"))
res=n1+n2
except ValueError:
print("Enter integers only...")
else:
print("The result is:",res)
Output:

Use of finally clause in exception handling in


Python
The finally clause ends the exception-handling process. It is the last clause after handling all
except clauses including else block. The finally clause always executes at the end. Example:

print ("Handling multiple exceptions")


try:
n1=int(input("Enter number1:"))
n2=int(input("Enter number2:"))
res=n1+n2
except ValueError:
print("Enter integers only...")
else:
print("No exception raised...")
print("The result is:",res)
finally:
print("You have done it!!! Bye Bye")

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:

print ("Handling multiple exceptions")


try:
n1=int(input("Enter number1:"))
n2=int(input("Enter number2:"))
res=n1/n2
except ZeroDivisionError:
print("Enter integers only...")
else:
print("No exception raised...")
print("The result is:",res)
finally:
print("You have done it!!! Bye Bye")

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.

You might also like