8 – Exception Handling in python

WHY EXCEPTIONAL HANDLING?

Exceptions are created when the normal flow of the program is interrupted. Exceptions should be handled immediately or the program stops executing. The code that is suspected to raise an exception is used with a try and except.

WITHOUT TRY-EXCEPT :

1
2
3
#Without exception
x=float(raw_input("Enter a Floating Point value "))
print x

OUTPUT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> 
Enter a Floating Point value 12.0
12.0
>>> ================================ RESTART ================================
>>> 
Enter a Floating Point value 1
1.0
>>> ================================ RESTART ================================
>>> 
Enter a Floating Point value ab
 
Traceback (most recent call last):
  File "C:/Python27/except.py", line 2, in <module>
    x=float(raw_input("Enter a Floating Point value "))
ValueError: could not convert string to float: ab
>>>

WITH TRY-EXCEPT:

1
2
3
4
5
6
#Without arguments
try:
    x=float(raw_input("Enter a Floating Point value "))
    print x
except ValueError:
    print "Enter a correct Floating Point value"

OUTPUT

1
2
3
4
>>> 
Enter a Floating Point value a
Enter a correct Floating Point value
>>>

WITH ARGUMENTS:

Arguments are used to know more about the exception that occurred. The value of exception differs from one exception to other. 

1
2
3
4
5
6
7
8
#With Arguments
 
try:
    y=int(raw_input("Enter a value "))
    print y
    y=10+"10"
except TypeError,e:
    print "Error = ",e

OUTPUT

1
2
3
4
5
>>> 
Enter a value 10
10
Error =  unsupported operand type(s) for +: 'int' and 'str'
>>>

FINALLY STATEMENT:

Code blocks in finally statement will be ensured to be executed always.

1
2
3
4
5
6
7
8
#With finally
try:
    x=float(raw_input("Enter a Floating Point value "))
    print x
except ValueError:
    print "Enter Floating point value" 
finally:
    print "Thank You"

OUTPUT

1
2
3
4
5
6
7
8
9
10
11
>>> 
Enter a Floating Point value 10
10.0
Thank You
 
>>> ================================ RESTART ================================
>>> 
Enter a Floating Point value a
Enter Floating point value
Thank You
>>>

MULTIPLE EXCEPTIONS:

Multiple Except statement can be used for a single try statement. 

1
2
3
4
5
6
7
try:
    x=float(raw_input("Enter a Floating Point value "))
    print x
except ValueError:
    print "Enter Floating point value" 
except KeyboardInterrupt:
    print "Programm stoped using CTRL+c"

OUTPUT

1
2
3
4
>>> 
Enter a Floating Point value 
Programm stoped using CTRL+c
>>>

ASSERT STATEMENT:

Assert Statement is like IF statement but if condition in assert statement fails an AssertionError is raised.

1
2
3
4
5
6
7
#With Assert Statement
try:
    x=float(raw_input("Enter a Floating Point value "))
    print x
    assert x<50
except AssertionError:
    print "Value greater than 50"

OUTPUT

1
2
3
4
5
6
7
8
9
>>> 
Enter a Floating Point value 10
10.0
>>> ================================ RESTART ================================
>>> 
Enter a Floating Point value 100
100.0
Value greater than 50
>>>

RAISING EXCEPTION:

Exceptions can be raised manually by using raise statement.

1
2
3
4
5
6
7
8
#With raise Statement
try:
    x=float(raw_input("Enter a Floating Point value "))
    print x
    if x>50:
        raise Exception('Value greater than 50')
except Exception as e:
    print e

OUTPUT

1
2
3
4
5
>>> 
Enter a Floating Point value 90
90.0
Value greater than 50" 
>>>

USER DEFINED EXCEPTION:

We can create our own excptions in python. A user-defined exception named Newerror is created below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#User defined exception named Newerror
class Newerror(Exception):
 
    def __init__(self, v):
        self.v = v
 
    def __str__(self):
        return(repr(self.v))
 
try:
    raise(Newerror(10))
 
except Newerror as e:
    print 'Exception occured: ',e.v

OUTPUT

1
2
3
>>> 
Exception occured:  10
>>>
THANKYOU
SHARE THIS!!!

Gowtham S

Gowtham is a programming enthusiast. His field of interest includes Arduino, NodeMCU, Raspberry Pi, and Python. To know more about him visit https://mybtechprojects.tech/about-us/.

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.