12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

When this code is run, the following output is produced. Trace through the code tosee how exception handling produces each of the test’s outputs here:------------------------------EXCEPTION RAISED AND CAUGHTexcept runfinally runafter run------------------------------NO EXCEPTION RAISEDfinally runafter run------------------------------NO EXCEPTION RAISED, ELSE RUNelse runfinally runafter run------------------------------EXCEPTION RAISED BUT NOT CAUGHTfinally runTraceback (most recent call last):File "C:/<strong>Python</strong>25/mergedexc.py", line 32, in x = 1 / 0ZeroDivisionError: integer division or modulo by zeroThis example uses built-in operations in the main action to trigger exceptions or not,and relies on the fact that <strong>Python</strong> always checks for errors as our code is running.The next section shows how to raise exceptions manually instead.The raise StatementTo trigger exceptions explicitly, you can code raise statements. Their general form issimple—a raise statement consists of the word raise, optionally followed by thename of the exception to be raised, and an optional extra data item to pass with theexception:raise raise , raise# Manually trigger an exception# Pass extra data to catcher too# Re-raise the most recent exceptionThe second form allows you to pass an extra data item along with the exception toprovide details for the handler. In the raise statement, the data is listed after theexception name; back in the try statement, the data is obtained by including a variableto receive it. For instance, if the try includes an except name, X: statement, thevariable X will be assigned the extra data item listed in the raise. The third raiseform simply reraises the current exception; it’s handy if you want to propagate anexception you’ve caught to another handler.592 | Chapter 27: Exception Basics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!