Python Exception

Exceptions handling in python is very similar to java.the code,which harbours risk of an exception,is embedded in a try block,but whereas in java exceptions are caught by catch clauses,we have statements introduced by an "except" keyword in python.it is possible to exceptions - with the raise statements it's possible to force a specified exception to occur.

Example

							
while True:
    try:
        a = raw_input("Please enter an integer: ")
        a = int(a)
        break
    except ValueError:
        print("No valid integer")
print "you entered an integer!"
						
							

Multiple Except Clauses

A try statements may have more than one except for different exceptions,but at most one except clause will be executed.In this example we discus on IOError and ValueError.

							
try:
    file = open('test.txt')
    s = file.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "No valid integer in line."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise
							
							
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!