Try and except

consider this short program:

Download construct/simpletry.cmd

... print 'error: no reciprocal' reciprocal of 0.3 is 3.33333333333 error: no reciprocal

The keywords try and except are used for error handling, just like if and else are used for conditionals. If nothing goes wrong, Python executes the code in the try block and then skips over the except block entirely (see Figure 12.2, on the following page). If any exceptions are raised in the try block, Python immediately jumps to the start of the except block and executes the code inside it. When this happens, we say that the exception has been caught and refer to the code that deals with it as an exception handler. Statements in the try block after the statement that raised the exception are not executed.

print 'error: no reciprocal'



(rest of program)

print 'error: no reciprocal'


4 print 'error: no reciprocal'

No Error

Division By Zero

Figure 12.2: Asimple try/except

We can also tell Python what to do when an exception isn't raised by adding an else block to the try/except:

Download construct/exceptelse.cmd

>>> invert(1) reciprocal of 1 is 1.0 >>> invert(0) caught exception for 0

Here, the statements in the else block are executed only if everything inside the try block was executed without error. If we were sure we knew all the places that exceptions could be thrown, we could put these statements inside the try block. Even then, it is often clearer to put them in an else block so that people reading the code can see that these statements are to be executed only if the try block completed normally.

Was this article helpful?

0 0

Post a comment