Python style: exceptions vs. sys.exit()

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Sep 24 22:03:43 EDT 2008


On Wed, 24 Sep 2008 10:54:40 -0500, Grant Edwards wrote:

> You're right.  I had forgotten that sys.exit() is actually raising the
> system exit exception, and that the application calling the library
> could handle that exception.

Could but shouldn't.

The exception hierarchy was re-designed in Python 2.5 specifically so 
that SystemExit and KeyboardInterrupt no longer inherit from Exception. 
That means this will do the right thing:

try:
    process(record)
    if changed:
        update(record)
except Exception:
    # don't write the record if any error occurs
    pass
    

Neither SystemExit nor KeyboardInterrupt are errors, and they should not 
be treated as errors. I quote from the Fine Manual:

[SystemExit] inherits from BaseException instead of StandardError or 
Exception so that it is not accidentally caught by code that catches 
Exception. This allows the exception to properly propagate up and cause 
the interpreter to exit.

http://docs.python.org/lib/module-exceptions.html

SystemExit is not an error. KeyboardInterrupt is not an error. Libraries 
should not use SystemExit to signal an error any more than they should 
use MemoryError to signal a missing attribute.

Whether or not an application exits is up to the application to decide, 
not the library it wraps. Libraries should report errors by raising an 
Exception (note the capital E), and the application should decide whether 
or not it is recoverable, and if not, exit (perhaps by simply not 
catching the exception).



-- 
Steven



More information about the Python-list mailing list