[Python-ideas] Block-Scoped Exception Handlers

Ethan Furman ethan at stoneleaf.us
Sat May 7 00:47:04 EDT 2016


On 05/06/2016 12:15 PM, Kyle Lahnakoski wrote:

> 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.
>
>
>
> For example, from ver_33.py (in Record._retrieve_field_value),
>
> ________try:
> ____________if null_data[byte] >> bit & 1:
> ________________return Null
> ________except IndexError:
> ____________print(null_data)
> ____________print(index)
> ____________print(byte, bit)
> ____________print(len(self._data), self._data)
> ____________print(null_def)
> ____________print(null_data)
> ____________raise
>
> It is not obvious to me that IndexError is the only Exception that can
> come from here.  This code may raise file access exceptions, HTTP
> exceptions, I do not know.   I would, at least, add a `raise Exception`
> clause to catch those unknown situations.   Furthermore, since I do not
> know how deep the stack will be on those exceptions, I would
> chain-and-raise

Firstly, my compliments for actually checking out the code I was 
referring to.  I'm impressed!

Secondly, that whole try/except, especially the multiple print 
statements, is an example of how to track down something -- but that is 
debugging code that I forgot take out.

In other words, I was getting an IndexError, so I stuck that code in for 
testing, fixed the problem... and forgot to remove the code.  To be 
fair, I was the primary consumer of that library for a long time.

So, as others have said:  Just write your code.  When something breaks, 
then put in the debugging code to see what exactly is going on.  If you 
don't already have a test suite, start one at that point: write the test 
that should succeed, watch it fail, fix your code, watch your test 
succeed, rest assured that if you break that test in the future you'll 
catch before you release your code in to the wild.

--
~Ethan~



More information about the Python-ideas mailing list