[Python-ideas] Fwd: Block-Scoped Exception Handlers

INADA Naoki songofacandy at gmail.com
Fri May 6 19:57:42 EDT 2016


> ____def process_todo(todo):________pre_process()________for t in todo:____________except Exception, e:________________break____________process(t)________post_process()
>
>
> As an alternative to
> ____def process_todo(todo):________pre_process()________for t in todo:____________try________________process(t)____________except Exception, e:________________break________post_process()
>
>
I don't feel former is quite readable than later.

Of course, a couple `try` nested statements make the indentation worse.
> For example, we wish to ignore problems in dealing with todo items, like
> above, but the todo items are complicated; each is a dict() of details.
> Failure to deal with one of the details is ignored, but the rest of the
> details are still attempted:
>
> def process_todo(todo):
> ____pre_process()
> ____for t in todo:
> ________except Exception, e:
> ____________break
> ________for u, v in t.items():
> ____________except Exception, e:
> ________________continue
> ____________process()
> ____post_process()
>
> Which is better than what I do now:
>
> def process_todo(todo):
> ____pre_process()
> ____for t in todo:
> ________try:
> ____________for u, v in t.items():
> ________________try:
> ____________________process()
> ________________except Exception, e:
> ____________________continue
> ________except Exception, e:
> ____________break
> ____post_process()
>
>
>
While later is more nested, it seems straightforward.

Additionally, try-catch pair should have minimum try block unlike
try-finally pair.
I am afraid of proposed syntax sugar misleads people to expand try block.

At a high level:  The `try/except/finally` is powerful structure.
> Realizing that the `try/finally` pair is very common leads to the creation
> of `with`. I am proposing the same logic for `try/catch` pair:  They are
> commonly paired together and should have an optimized syntax.
>
> try-catch pair shouldn't used so many like try-finally pairs.

When function call is very nested, only function near top level should
catch Exceptions.
Most of middle~bottom level functions use only finally (or with statement,
off course).

If many functions have catch clause, it's a very bad code smell.

C# and Java have syntax sugar only for try-finally pair too.
(using statement in C# and try with resource in Java).


-- 
INADA Naoki  <songofacandy at gmail.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160507/0cf75ded/attachment.html>


More information about the Python-ideas mailing list