Main.Exceptions History

Hide minor edits - Show changes to markup

April 18, 2013, at 02:34 PM MST by 129.82.44.223 -
Changed line 67 from:
  1. each exception has a type, that identifies the nature of the error
to:
  1. the name of the exception identifies the nature of the error
March 02, 2010, at 03:05 PM MST by 10.84.44.82 -
Added lines 1-71:

(:source lang=python:)

"""Exceptions http://openbookproject.net/thinkcs/python/english2e/ch11.html#exceptions See also: http://docs.python.org/tutorial/errors.html """

  1. Whenever a runtime error occurs, it creates an exception.
  2. The program stops running and Python prints out the traceback,
  3. which ends with the exception that occured.
  4. Dividing by zero creates an exception:

print 1/0

  1. And so does accessing a nonexistent element in a list:

a = [] print a[5]

  1. As does trying to modify a string:

s = 'python' s[0] = 'j'

  1. Sometimes we want to execute an operation that might cause an exception,
  2. but we don't want the program to stop. We can handle the exception using
  3. the try and except statements.
  4. For example:

file_name = raw_input('Enter a file name: ') try:

    file_handle = open(file_name, "r")

except:

    print 'There is no file named', filename

def exists(file_name):

    try:
        f = open(file_name)
        f.close()
        return True
    except:
        return False
  1. Here's a snippet of code that prompts the user for a number and
  2. continues to ask for a number until a valid number is provided

while True:

    try:
        x = int(raw_input("Please enter an integer: "))
        break
    except ValueError:
        print "Oops!  That was no valid number.  Try again..."
  1. note the use of the break statement - it exits the loop in which
  2. it is put
  3. the 'raise' statement is used to create an exception:

age = input('Please enter your age: ') if age < 0:

    raise ValueError, ' age
  1. each exception has a type, that identifies the nature of the error
  2. A complete list of exceptions is found at:
  3. http://docs.python.org/library/exceptions.html

(:sourceend:)