confusion about Exception Mechanism

Samuel Walters swalters_usenet at yahoo.com
Thu Jan 15 01:06:47 EST 2004


| Zachary said |

> Hello,
> I'm relatively new at Python, and am slightly confused about how the
> try...except mechanism is supposed to work.  I am just not sure how it
> would be used, as it just seems that it is another sort of loop.  Is their
> any sort of example I could look at, that has an example of how it is
> applied? I haven't really seen any such full example. Thanks, And Sorry
> for the newbie Question, Zack

When I first encountered exceptions, they were a bit confusing for me too.

Exceptions are failsafes that allow a program to sensibly deal with
errors.  When something goes wrong, Python won't just spit out an error
message.  First it "raises an exception."  You may also hear people call
that throwing an exception.  A try block allows you to "catch" that
exception and deal with it yourself.  In a way, it's the program sending
out a cry for help.  By putting something in a try block, you're saying
that you're willing to answer that cry.

For instance: (stolen from the tutorial page)

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except ValueError:
    print "Could not convert data to an integer."
except IOError, (errno, strerror):
    print "I/O error(%s): %s" % (errno, strerror)
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise


You put the code you're willing to handle exceptions (errors) for between
try and except.  The first except (there only needs to be one, there may
be multiple) says that if the block of code encounters a "ValueError" problem,
that we will print "Could not convert data to an integer." and then keeps
moving along in the program.  The second except block handles IOError
exceptions, and also gets some extra information from those exceptions. 
It stores this extra information in "errno" and "strerror".  It then
prints some information about what exactly went wrong and continues
running the program.  The last except block catches any and every error
that wasn't caught before it.  It will print an error message, then the
statement "raise" falls back on the next line of defense of errors.  Since
this bit of code may itself be inside a try block, maybe the program will
handle it elsewhere.  If there's no other try blocks to handle an
exception, then, and only then, will Python spit out an error message and
stop the program.

There's other pieces to this puzzle, but they're all on the tutorial page
pointed out elsewhere.  Hopefully this will give you some sense of bearing
while reading that.

HTH

Sam Walters.

-- 
Never forget the halloween documents.
http://www.opensource.org/halloween/
""" Where will Microsoft try to drag you today?
    Do you really want to go there?"""




More information about the Python-list mailing list