Handling Exceptions

It is possible to write programs that handle exceptions.

#!/usr/bin/python
import sys

def usage():
    print 'Usage: %s <file>' % sys.argv[0]
    sys.exit(2)

if len(sys.argv) != 2:
    usage()

filename = sys.argv[1]

try:
    f = open(filename)
    print 'Opening `%s` for reading...' % filename
except:
    print 'Could not open `%s` for reading.' % filename
    print 'Using default file instead.'
    try:
        f = open('default.txt')
    except:
        print 'Could not open `default.txt` either.  Exiting'
        sys.exit(1)

print f.read()
f.close()