[Tutor] Puzzling case of assertRaises not running properly

Steven D'Aprano steve at pearwood.info
Sat Dec 31 01:15:19 EST 2016

On Fri, Dec 30, 2016 at 09:51:46PM +0000, angela ebirim wrote:

> class Bill(object):
>    def tax(self, total):
>      tax = float(total * 0.05)
>      return round(tax, 2)
>    def check_input(self, seat1, app1):
>      try:
>         seat1 = float(seat1)
>         app1 = float(app1)
>      except ValueError:
>          print "Not a float"
>      return (seat1, app1)

Here is your problem. The check_input method doesn't raise ValueError.

*Internally* it gets raised, but then the exception is caught, a 
completely useless message is mysteriously printed ("Not a float" -- 
what's not a float? what is expecting a float?) and the method continues 
as if nothing had happened, only to fail later on with some other error.

Because the ValueError is caught and discarded, there's no ValueError 
for your unit test to catch. Hence the test fails.

(1) The first rule of catching exceptions is: Don't.

(2) The second rule, for experts: If you must, but only if you can 
    recover from the error.

Of course in real life sometimes we do catch exceptions, that's why 
Python has a try...except command so that they can be caught.

But too many people think that the solution to programming bugs is to 
surround everything with try...except, catch the exception, print a 
useless error message (or worse, don't print anything!) and then try to 
continue. It never works, of course, it just makes the code even harder 
to debug. 

As a beginner, before you write a try...except code, you should take a 
quick run around the block followed by a cold shower. If you still think 
you need a try...except block, then *maybe* you can use it.

But as a beginner, you should think that 
exceptions are your best friend in the world. Exceptions show when you 
have made a programming error, or passed the wrong data. How can you fix 
the bug if you don't know where it is? Catching exceptions should be 
done only rarely, when you absolutely need to, because you can recover 
from the error and continue. Never[1] catch an exception just to print a 
bland, boring error message and then continue.

[1] For expert programmers, never say never. Experts know when to break 
the rules.


More information about the Tutor mailing list