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 is possible to exceptions - with the raise statements it's possible to force a specified exception to occur.


while True:
        a = raw_input("Please enter an integer: ")
        a = int(a)
    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.

    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."
    print "Unexpected error:", sys.exc_info()[0]
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!