15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

except Exception, e:<br />

# handle real errors<br />

If you really want to catch all errors, you can still do that too, but use BaseException instead:<br />

try:<br />

:<br />

except BaseException, e:<br />

# handle all errors<br />

And of course, there is the less preferred bare except.<br />

<strong>Core</strong> Style: Do not handle and ignore all errors<br />

The try-except statement has been included in <strong>Python</strong> to provide a<br />

powerful mechanism for programmers to track down potential errors<br />

and perhaps to provide logic within the code to handle situations<br />

where it may not otherwise be possible, for example, in C. The main<br />

idea is to minimize the number of errors and still maintain program<br />

correctness. As with all tools, they must be used properly.<br />

One incorrect use of TRy-except is to serve as a giant bandage over<br />

large pieces of code. By that we mean putting large blocks, if not your<br />

entire source code, within a try and/or have a large generic except to<br />

"filter" any fatal errors by ignoring them:<br />

# this is really bad code<br />

try:<br />

large_block_of_code # bandage of large piece of code<br />

except Exception: # same as except:<br />

pass # blind eye ignoring all errors<br />

Obviously, errors cannot be avoided, and the job of TRy-except is to<br />

provide a mechanism whereby an acceptable problem can be remedied<br />

or properly dealt with, and not be used as a filter. The construct above<br />

will hide many errors, but this type of usage promotes a poor<br />

engineering practice that we certainly cannot endorse.<br />

Bottom line: Avoid using try-except around a large block of code with<br />

a pass just to hide errors. Instead, either handle specific exceptions<br />

and ignore them (pass), or handle all errors and take a specific action.<br />

Do not do both (handle all errors, ignore all errors).<br />

10.3.6. "Exceptional Arguments"<br />

No, the title of this section has nothing to do with having a major fight. Instead, we are referring to the<br />

fact that an exception may have an argument or reason passed along to the exception handler when<br />

they are raised. When an exception is raised, parameters are generally provided as an additional aid for

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

Saved successfully!

Ooh no, something went wrong!