Exception Handling in python with examples

By

 Python Exception:-

  • An exception is an unusal things in a program that cause the interruption in flow of program.
  • An exception is the run-time errors that are unable to handle the python program.
  • While creating and executing a python script things may go worng at two different stages:-
  1. During compilation
  2. During execution

  • Error that occurs during compilation time,are called syntax error.The Error that occurs during execution or run time, are called exceptions or run-time error.
  • Python provides a way to handle the exception so that the program/codes can be executed without any interruption.
  • Python has many built-in exceptions that enable or program to run without interruption and give the output of the code.
Some Run-time  errors in python:-
1.)  Memory related erros
  • stack overflow
  • Heap overflow
  • Exceeding array bounds
2.) Arithmetic related errors
  • Divide by zero
  • Arithmetic overflow/underflow
3.) other errors:
  • Attempt to use an unassigned reference.
  • File not found

Common standard  built-in Exceptions:

Python provides the some built-in exceptions as given below:-

1.) ZeroDivisionError:- This  error occurs when a number is divided by zero.

2.) IndentationError:- This error occurs when user gives the incorrect indentation in python program.

3.) IOError:-This error occurs when input output operation fails.

4.) NameError:- This error occurs when a name is not found in given program.It may be local or global.

5.) EOFError:-This error occurs when the end of the file is reached and yet operation are being performed.

Example:-

We already know that the execution is an unusual things that halts the execution of the program.

e.g.

a=int(input("Enter the first number: "))
b=int(input("Enter the second number: "))
result=a/b
print("output=",result)
print("welcome to MNTLAB")
Output:-

Enter the first number: 50

Enter the second number: 10

output= 5.0

welcome to MNTLAB

>>> 

============= RESTART: C:/Users/RAMASHANKER VERMA/Desktop/error.py =============

Enter the first number: 20

Enter the second number: 0

Traceback (most recent call last):

  File "C:/Users/RAMASHANKER VERMA/Desktop/error.py", line 3, in <module>

    result=a/b

ZeroDivisionError: division by zero

>>> 

Descriptions:-

  • When user run this program and put the values:-

a=50

b=10

then the result=5 printed on the screen whitout any exception.

  • When user run the program again and put the values:-
a=20
b=0
then the program throw the error because of unusual inputs.To sove this type of problem,we will use Exceptional handling in python.We will discuss it in below.

Exception Handling:-

try and except blocks ar used to deal with an exception.

1.)  try block :-If the python programs contains some suspicious code that may throw the exception, we will place that code in try block.

2.) exception block:- It is used to catch the raised exception.It must immediatly folow the try block.

why we use Exception Handling in python:-

  • Suppose we have a program codes and we want to run this if codes give unspected error.
  • We already know if a program gets error then it stop the execution.
  • If we use exception handling concept then we can easily handle these errors and program executed at the end.
  • Python provides two types of exception handling first is Built-in exception
  • second is user-defined or custom  exception.
e.g.

a=int (input("Enter a number: "))
b=int (input("Enter a number: "))
result=a/b
print("Output of a/b=",result) 
Output:-
Enter a number: 42
Enter a number: 0
Traceback (most recent call last):
  File "C:\Users\RAMASHANKER VERMA\Desktop\without exception handling.py", line 3, in <module>
    result=a/b
ZeroDivisionError: division by zero
>>> 
Note:-To handle these unspected errors we generally use this exception handling in python as given below:-
  • exception

Syntax:-
try:
    #block of codes
except Exception1:
    #block of codes
except Exception2:
    #block of codes
except Exception3:
    #block of codes
 ....................   
other codes

e.g.

try:
    a=int (input("Enter a number: "))
    b=int (input("Enter a number: "))
    result=a/b
    print("Output of a/b=",result)
except:
        print("Denominator(b)value can't zero")
Output:-
Enter a number: 10
Enter a number: 5
Output of a/b= 2.0
>>> 
=========== RESTART: C:/Users/RAMASHANKER VERMA/Desktop/try block.py ===========
Enter a number: 25
Enter a number: 0
Denominator(b)value can't zero
>>> 
Note:-
  • If no exception occurs while executing the try block,control goes to the next line after skip the except block.
  • If an exception occurs during execution of statements in try block,an exception is raised and rest of the try block is skipped.Now control goes to the matched except block that except block is executed.
  • If an exception occurs which does not match the exception named in except block,then the default exception handler catches the exception,print the exception and terminates execution.
  • When exception is rasised and except block is executed,control goes to the next line after except block,unless there is a return or raise in except block.

3.) else block :- This else block codes will be executed if the try block codes executed successfully without any error. Then the control jump to the next line of except block.

  • We can also use else statement after the try-except statement.
  • This else block codes are executed if no execution occurs in the try block.


Syntax:-

try:
    #block of codes
except Exception1:
    #block of codes
except Exception2:
    #block of codes
except Exception3:
    #block of codes
else:
    #block of codes

e.g.

try:
    a=int (input("Enter a number: "))
    b=int (input("Enter a number: "))
    result=a/b
    print("Output of a/b=",result)
except Exception1:
        print("Any number can't dvide by zero")
else:
    print("Welcome to else block statement")
Output:-
Enter a number: 5
Enter a number: 2
Output of a/b= 2.5
Welcome to else block statement
>>> 

The except statement using with exception variable

We can use the exception variable with the except statement.This is used by using the as keyword as shown below:-

e.g.

try:
    a=int (input("Enter a number: "))
    b=int (input("Enter a number: "))
    c=a/b
    print("Output of a/b=",c)
except ZeroDivisionError as e1:
        print("Value of 'b' cant not zero")
        print(e1.args)
        print(e1)
except ValueError:
    print("Unable to convert string to int")
except:
    print("some unknown error")
else:
    print("Welcome to else block statement")
Output:-

Enter a number: 10

Enter a number: 5

Output of a/b= 2.0

Welcome to else block statement

>>> 

=========== RESTART: C:\Users\RAMASHANKER VERMA\Desktop\try block.py ===========

Enter a number: 20

Enter a number: 0

Value of 'b' cant not zero

('division by zero',)

division by zero

>>> 

=========== RESTART: C:\Users\RAMASHANKER VERMA\Desktop\try block.py ===========

Enter a number: 30

Enter a number: ram

Unable to convert string to int

>>> 

Note:-

  • If an exception occurs,the type of excetion raised is matched with the exceptions named after except keyword.When a match occurs,the except block is executed and then exection continued after the last except block.
  • We can use the keyword as to receive the exception object.Then we can occurs its argument either using its args variable,or by simply using the execution object.
  • args actually refers to arguments that were used while creating the exception object.

e.g.

try:
    #Throw an exception if the file does not exist
    file_ptr=open("file.txt","r")
except IOError:
    print("This file is not found")
else:
    print("This file opened successfully")
    file_ptr.close()
Output:-

This file is not found

>>> 

Now Create a file.txt  file on your desktop and Run the program again.You  will see following output as shown beloew:

Output:-

This file opened successfully

>>> 

Declaring Multiple Exceptions:-

The python allows us to declare the multiple exceptions with the except clause.This case is useful where a try block throws multiple exceptions.To catch these multiple exception of try block,we will use multiple exceptions as given below:-

Syntax:-

try:
    #block of code
except(<Exception1>,<Exception2>,<Exception3>,<Exception4>,...<Exceptionn>):
    #block of code
else:
    #block of code

e.g.

try:
    a=int(input("Enter the first number: "))
    b=int(input("Enter the second number: "))
    c=a/b
    print("Value of c= ",c)
except(ArithmeticError,IOError,ValueError):
    print("An Exception occurs")
else:
    print("Welcome to MNTLAB")

Output:-

Enter the first number: 5

Enter the second number: 2

Value of c=  2.5

Welcome to MNTLAB

>>> 

============= RESTART: C:/Users/RAMASHANKER VERMA/Desktop/error.py =============

Enter the first number: 5

Enter the second number: 0

An Exception occurs

>>> 

============= RESTART: C:/Users/RAMASHANKER VERMA/Desktop/error.py =============

Enter the first number: 50

Enter the second number: ram

An Exception occurs

>>> 

Finally Block

  • Finally block is optinal which is used with try statement.
  • Finally block code always runs,no matter what! Even if return or break occurs first.
  • In python,finally block is placed after except blocks(if they exist in python code).
  • try block must have except block and /or finally block.
  • Finally block is executed no matter what exception occur in the program.
  • Finally block is used to release the external resources like files,network connections or database connections.

  • Finally block provides a guarantee of the execution.   

Syntax:-

try:
    #block of code
    #It may throws exceptions
except:
    #block of code
    #This block code will be executed if an exception occurs
finally:
    #block of code
    #This block code wil be executed always

e.g.

try:
    file_ptr=open("file.txt","r")
    file_ptr.write("welcome to MNTLAB")
except:
    print("An Errors occurs")
    print("Welcome to MNTLAB")    
finally:
    file_ptr.close()
    print("file is closed successfully")
Output:-

An Errors occurs

Welcome to MNTLAB

file is closed successfully

>>> 

Raising exception:-

An exception can be raised manually/forcefully by using the raise clause in python.Some times we have to raise an exception to stop the execution of the program.Then we use this raise clause to raise an exception in python.

Syntax:-

raise Exception-class<value>

e.g.

try:
    n=int(input("Enter an even number: "))
    if(n%2!=0):
        raise ValueError("That is odd number")
    else:
        print("That value is even number ")
except ValueError as e:
    print(e)
Output:

Enter an even number: 7

That is odd number

>>> 

============ RESTART: C:/Users/RAMASHANKER VERMA/Desktop/program1.py ===========

Enter an even number: 8

That value is even number 

>>> 

e.g.

try:
    a=int(input("Enter a number: "))
    b=int(input("Enter second number: "))
    if b is 0:
        raise ArithmeticError
    else:
        print("value of a/b=",a/b)
except ArithmeticError:
    print("The value of b can not be error(0)")
Output:

Enter a number: 80

Enter second number: 0

The value of b can not be error 0

>>> 

User-defined Exception/custom Exception in python

  • We already know all exceptional conditions can not be occured for every exceptional condition there can not be a class in python library.
  • To handle these cases we can define our own exception class.
  • Here we will create our exceptions that can be reaised from the program and we will caught it by using except class as shown in the following program.
e.g.
class custom_error(Exception):
    def __init__(self,data):
        self.data=data
    def __str__(self):
        return repr(self.data)
try:
    raise custom_error("custom error occured")
except custom_error as e:
    print("Error occured\n",e.data)   
Output:-
Error occured
 custom error occured
>>> 

For More...

0 comments:

Post a Comment

Powered by Blogger.