[Tutor] capturing errors/exceptions..
Steven D'Aprano
steve at pearwood.info
Fri Aug 1 16:54:18 CEST 2014
On Fri, Aug 01, 2014 at 10:14:38AM -0400, bruce wrote:
> Hi.
>
> Really basic question!!
>
> Got a chunk of some test python, trying to figure out a quick/easy way
> to capture all/any errors/exceptions that get thrown..
Why do you want to do that? The answer to your question will depend on
what you expect to do with the exception once you've caught it, and the
answer might very well be "don't do that".
> For the test process, I need to "ensure" that I capture any/all
> potential errors..
Hmmm. I don't quite see the reason for this.
If you're running by hand, manually, surely you want to see the
exceptions so that you can fix them? If there's an exception, what do
you expect to do next?
If you're using the unittest module, it already captures the exceptions
for you, no need to re-invent the wheel.
> -Could/Should I wrap the entire func in a try/catch when I call the
> function from the parent process?
You mean something like this?
try:
mymodule.function_being_test(x, y, z)
except Exception:
do_something_with_exception()
Sure. Sounds reasonable, if you have something reasonable to do once
you've captured the exception.
> -Should I have separate try/catch blocks within the function?
No. That means that the function is constrained by the testing regime.
> -The test py app is being run from the CLI, is there a py command line
> attribute that auto captures all errors?
No. How would such a thing work? In general, once an exception occurs,
you get a cascade of irrelevant errors:
n = lne(some_data) # Oops I meant len
m = 2*n + 1 # oops, this fails because n doesn't exist
value = something[m] # now this fails because m doesn't exist
...
Automatically recovering from an exception and continuing is not
practical, hence Python halts after an exception unless you take steps
to handle it yourself.
--
Steven
More information about the Tutor
mailing list