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.

etval = None<br />

return retval<br />

Bear in mind that with our change above, nothing about our code changed except that we used one<br />

more local variable. In designing a well-written application programmer interface (API), you may have<br />

kept the return value more flexible. Perhaps you documented that if a proper argument was passed to<br />

safe_float(), then indeed, a floating point number would be returned, but in the case of an error, you<br />

chose to return a string indicating the problem with the input value. We modify our code one more time<br />

to reflect this change:<br />

def safe_float(obj):<br />

try:<br />

retval = float(obj)<br />

except ValueError:<br />

retval = 'could not convert non-number to float'<br />

return retval<br />

The only thing we changed in the example was to return an error string as opposed to just None. We<br />

should take our function out for a test drive to see how well it works so far:<br />

>>> safe_float('12.34')<br />

12.34<br />

>>> safe_float('bad input')<br />

'could not convert non-number to float'<br />

We made a good startnow we can detect invalid string input, but we are still vulnerable to invalid<br />

objects being passed in:<br />

>>> safe_float({'a': 'Dict'})<br />

Traceback (innermost last):<br />

File "", line 3, in ?<br />

retval = float(obj)<br />

TypeError: float() argument must be a string or a number<br />

We will address this final shortcoming momentarily, but before we further modify our example, we<br />

would like to highlight the flexibility of the try-except syntax, especially the except statement, which<br />

comes in a few more flavors.<br />

10.3.3. try Statement with Multiple excepts<br />

Earlier in this chapter, we introduced the following general syntax for except:<br />

except Exception[, reason]:<br />

suite_for_exception_Exception<br />

The except statement in such formats specifically detects exceptions named Exception. You can chain<br />

multiple except statements together to handle different types of exceptions with the same TRy:

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

Saved successfully!

Ooh no, something went wrong!