Exception Handling in Python

Documentation about Exceptions look for 5.2. Concrete exceptions to find the list

Some Error names - watch capitalization!

Try to keep the "try block" as small and focused as possible, so that you only have to check for an error or two. Putting your entire program in a "try block" may stop it from crashing, BUT you will have to figure out which error caused the exception, and do something useful for it.

Examples:

Getting a valid filename

def main():
    fn = input("Enter a filename ")
    IOok = False
    while not IOok:
         try:
            infile = open(fn,"r")
            IOok = True
         except IOError:
            print("Error, file would not open")
            fn = input("Enter a filename ")

    # at this point infile is a valid file, open for reading
    # and fn is the external name for the file
main()

example of error caused by division by zero

	def main():
	     try:
                x = 0
                y = 7
                print(y/x)
             except:
                print("x was 0")
	     print("next")
	main()

Example of more than one error caught

from math import *

def main():
    try:
        x = -10
        y = 7
        print(sqrt(y/x))
    except ZeroDivisionError:
        print("dividing by zero!")
    except ValueError:
        print("sqrt does not take negatives")
    print("last")

main()