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.

The try/else ClauseAt first glance, the purpose of the else clause is not always obvious to <strong>Python</strong>newcomers. Without it, though, there is no way to tell (without setting and checkingBoolean flags) whether the flow of control has proceeded past a try statement becauseno exception was raised, or because an exception occurred and was handled:try:...run code...except IndexError:...handle exception...# Did we get here because the try failed or not?Much like the way else clauses in loops make the exit cause more apparent, the elseclause provides syntax in a try that makes what has happened obvious andunambiguous:try:...run code...except IndexError:...handle exception...else:...no exception occurred...You can almost emulate an else clause by moving its code into the try block:try:...run code......no exception occurred...except IndexError:...handle exception...This can lead to incorrect exception classifications, though. If the “no exceptionoccurred” action triggers an IndexError, it will register as a failure of the try block,and hence erroneously trigger the exception handler below the try (subtle, but true!).By using an explicit else clause instead, you make the logic more obvious, and guaranteethat except handlers will run only for real failures in the code you’re wrappingin a try, not for failures in the else case’s action.Example: Default BehaviorBecause the control flow through a program is easier to capture in <strong>Python</strong> than inEnglish, let’s run some examples that further illustrate exception basics. I’ve mentionedthat exceptions not caught by try statements percolate up to the top level ofthe <strong>Python</strong> process, and run <strong>Python</strong>’s default exception-handling logic (i.e., <strong>Python</strong>terminates the running program, and prints a standard error message). Let’s look atan example. Running the following module, bad.py, generates a divide-by-zeroexception:def gobad(x, y):return x / yThe try/except/else Statement | 585

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

Saved successfully!

Ooh no, something went wrong!