FAQs on the exercise Assert Methods III: Exception and Warning Methods
There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply () below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply () below!
You can also find further discussion and get answers to your questions over in Language Help.
Agree with a comment or answer? Like () to up-vote the contribution!
Hello! I’ve recently started to learn Python. Could anybody explain why this code (with argument of function in parentheses exactly) isn’t working? Thank you.
class PowerError(Exception):
pass
def power_outage_detected(outage_detected):
if outage_detected:
raise PowerError('A power outage has been detected somewhere in the system')
else:
print('All systems receiving power')
Apologies for a delayed reply but that is not a valid alternative. The function(functionArguments) call is evaluated before the .assertRaises method is called so the there is uncaught exception instead of the actual test.
In the unittest framework it will handle the error (so other tests can still be run) but you will not get the expected pass/fail results for that test. The correct syntax is the one given above.
From the documentation these are the two valid call signatures-
I should probably add that second call signature would be used in the following way-
...
with self.assertRaises(specificException):
function(functionArrguments)
In this way you can directly call your function with the relevant arguments (some people prefer that style) and wait for an exception where the context manager handles it instead. In this way your tests follow the standard pass/fail steps again (no loose exceptions).
As per the docs on unittest.TestCase.assertRaises this might be useful if you wanted to get more testing done on the exception itself as you can temporarily name the exception thrown-
with self.assertRaises(specificException) as error:
function(functionArrguments)
# then use something like
self.assertSomething(error.attribute)
# docs have a better example, worth a look
Agreed, but someone should remove this from the exercise hints, since it pretty clearly implies that the OPs syntax is also acceptable, but is apparently not true: