Skip to content Skip to sidebar Skip to footer

Passing Exceptions Across Classes While Unit-testing In Python

Assume two Python classes, the first of which (Class 1) contains a function (function_c1) that encompasses some statement (some_statement), which - if true - returns a customized e

Solution 1:

In order for an exception to be catchable, you have to raise it. If you return it, the exception acts like any other python object (and doesn't get caught in a try block.

classClass1:
    ''' My nifty class 1. '''def__init__(self):
        passdeffunction_c1(self, some_input):
        ''' A function of class 1. '''if some_statement(some_input):
            raise MyException('Some error message.')
        returnTrue

To address your comment below, for unit-testing with python's unittest module, you'd probably do something like this:

with self.assertRaises(MyException):
    Class1().function_c1(...)

If you're stuck in a pre-python2.7 environment, it would be:

self.assertRaises(MyException, Class1().function_c1, ...)

But for your sake, I hope you can use python2.7 at least :-).

Post a Comment for "Passing Exceptions Across Classes While Unit-testing In Python"