try-except Statement in Python

The try-except statement (and more complicated versions of this statement) allows you to define a section of code to monitor for exceptions and also provides the mechanism to execute handlers for exceptions.
The syntax for the most general try-except statement looks like this:

    try_suite # watch for exceptions here
except Exception:
    except_suite # exception-handling code

Let us give one example, then explain how things work. We will use our IOError example from above. We can make our code more robust by adding a try-except “wrapper” around the code:

    f = open('sampleFile')
except IOError:
    print 'could not open file'

As you can see, our code now runs seemingly without errors. In actuality, the same IOError still occurred when we attempted to open the nonexistent file. The difference? We added code to both detect and handle the error. When the IOError exception was raised, all we told the interpreter to do was to output a diagnostic message.


You may also like...

No © Loop and Break