[Python-ideas] Consistent programming error handling idiom

Steven D'Aprano steve at pearwood.info
Fri Apr 8 15:30:13 EDT 2016


On Fri, Apr 08, 2016 at 11:24:15AM -0700, rian at thelig.ht wrote:

> I want to live in a world where I can do this:
> 
>     while cbs:
>         cb = cbs.pop()
>         try:
>             cb()
>         except Exception as e:
>             logging.exception("In main loop")
>             if is_a_bug(e):
>                 raise SystemExit() from e

And I want a pony :-)

So long as Python allows people to write code like this:

# A deliberately silly example
if len(seq) == 0:
    raise ImportError("assertion fails")

you cannot expect to automatically know what an exception means without 
any context of where it came from and why it happened. The above example 
is silly, but it doesn't take much effort to come up with more serious 
ones:

- an interpreter written in Python may raise SyntaxError, which 
  is not a bug in the interpreter;

- a test framework may raise AssertionError for a failed test,
  which is not a bug in the framework;

- a function may raise MemoryError if the call *would* run out of
  memory, but without actually running out of memory; consequently
  it is not a fatal error, while another function may raise the 
  same MemoryError because it actually did fatally run out of memory.

Effectively, you want the compiler to Do What I Mean when it comes to 
exceptions. DWIM may, occasionally, be a good idea in applications, but 
I maintain it is never a good idea in a programming language. 

http://www.catb.org/jargon/html/D/DWIM.html

I'm afraid that there's no hope for it: you're going to have to actually 
understand where an exception came from, and why it happened, before 
deciding whether or not it can be recovered from. The interpreter can't 
do that for you.


-- 
Steve


More information about the Python-ideas mailing list