How to test that an exception is raised ?

Dan Perl danperl at rogers.com
Fri Jan 28 08:54:28 EST 2005


"StepH" <stephane.bronsart at bea.be> wrote in message 
news:41fa400b$0$2029$6c56d894 at feed0.news.be.easynet.net...
>
> Do you say that it's not possible to test (using unittest) if an exception
> is well raised if the tested code catch it ?
> How to solve this paradoxe ?  How to automaticaly test such code ?

Then you need a side-effect in catching the exception.  A return code would 
be such a side-effect.  Setting a state variable that can be checked by the 
invoking code would be another such side-effect.

> 1./ Cheking error-return value if not a good idea for me, cause this make
> the code less clear.  I don't want a code where i've to test each function
> return value...
> 2./ If I re-raise the exception, then how to not show the traceback.  My
> user will became crazy if they view such error msg.

But then how will the user know if the call did what it is supposed to do? 
And if the user mis-used the function and used it for a file that does not 
exist, how is he/she supposed to know what the problem was and why nothing 
is coming out of calling your function?

> It seems that there is 2 school here.  I've read a lot on python, and 
> somed
> 'guru' Python say that it's maybe better to use exception even for case 
> you
> can "predict", no ?  Or i'm completly wrong ?

The IOError is an exception that you can predict and I was saying that you 
should catch it, but with a "except IOError:" statement instead of the 
"except:" statement that you used. 





More information about the Python-list mailing list