[Python-ideas] Block-Scoped Exception Handlers
Chris Angelico
rosuav at gmail.com
Fri May 6 20:39:39 EDT 2016
On Sat, May 7, 2016 at 5:15 AM, Kyle Lahnakoski <klahnakoski at mozilla.com> wrote:
> This is a good point. There are probably domains that have clear
> inputs, or have a mature codebase, with tests covering all input
> permutations. These domains do not need `try` statements to cover the
> unknown. Maybe these domains dominate the universe of source code, and
> I am in the minority. I can easily be convince this is the case: I
> have seen lots of code that really does not care if an exception gets
> raised. Understanding why it failed is a real pain, for there are no
> descriptions, no summary, original causes are not chained, or if they
> are, the stack trace is missing. My code has no hope of mitigating
> those errors: It can not retry on HTTP errors, or provide useful
> feedback if the original cause is a missing file.
>
> Your strategy of simply not using `try` statements, may also work.
> Although, I do not know how you trace down the cause of errors on
> production systems easily without them. Mature software will not have
> as many logic errors as my green code, so the cost of chasing down a
> problem is better amortized, and it more reasonable to leave out `try`
> blocks.
It's nothing to do with the maturity of the codebase. It's more a
question of effort-for-effort. You have a couple of options:
1) Put in heaps of effort up front, and during code editing; or
2) Put in a bit more effort in debugging.
When you first write code, don't bother with any of the extra
boiler-plate. Just let the exceptions propagate as they are, and worry
about debugging when you get to it. Later on, follow the basic Rule of
Three: if you've done the same thing three times, put in some effort
to make it easier (because something you do three times is likely to
happen a fourth). Most of your code won't need extra exception info -
the traceback will serve you just fine. Once you've had three examples
of some particular loop tripping you up (because your debugging work
is harder due to not knowing which iteration of the loop raised the
exception), you know where to put in a simple exception-chaining
block:
import random
class InfoCarrier(Exception): pass
for i in range(30):
x = random.randrange(20)
try:
y = 1/x
except:
raise InfoCarrier("x = %s" % x)
You almost certainly do _not_ need this kind of construct all through
your code; that's too much effort in code maintenance for not enough
benefit in debugging. If you really think you need this kind of locals
inspection everywhere, pick up one of the execution frameworks that
lets you do this - I think ipython does? - and have none of it in your
code at all.
You're using Python. So stop writing so much code. :)
ChrisA
More information about the Python-ideas
mailing list