How to test that an exception is raised ?
Dan Perl
danperl at rogers.com
Fri Jan 28 16:50:39 EST 2005
"StepH" <stephane.bronsart at teledisnet.be> wrote in message
news:41faa68f$0$17406$4d4efb8e at read.news.be.uu.net...
> So why the assertRaises function in unittest ? My goal is to test if an
> exception is well raised when a bad filename is passed to the mps2xml
> function.
It is for functions in which the exception is raised and not caught. You
can use the exception mechanism to let the code invoking your function know
that something "exceptional" has happened. It means that you "throw" that
exception to the invoking code which has to catch it. Maybe the terminology
is poorly chosen, but assertRaises does not check whether an exception is
raised inside the function but only that an exception is raised (or
"thrown", as described by other languages) from inside the function to
outside. A function does not "throw" an exception if the exception is
caught inside the function. Is that clearer now?
In java for instance, functions are actually declared to "throw" an
exception if any operation inside the function may throw that exception and
the exception is not caught inside the function. If you implement a
function A that invokes another function B and B throws an exception of type
C, then you must catch the exception C in A or you have to declare A that it
"throws C".
Hope this helps.
Dan
More information about the Python-list
mailing list