Why no try-except-finally ?

Peter Hansen peter at engcorp.com
Wed Nov 5 21:59:00 CET 2003

KefX wrote:
> >Somewhat better style, generally, IMHO, would be to replace "err_code = 1"
> >with "raise" in the above.  Consider returning error codes to be a
> >parallel (and somewhat obsolescent) way of communicating failures to
> >calling code.  Raising an exception should be generally preferred.
> I agree with you in general, but this code is in my main() function, and
> returning an error code one way or another is the only way to report the error
> status to the OS. :)
> Instead of this:
> if __name__ == '__main__':
>     main()
> my code does this:
> if __name == '__main__':
>     sys.exit(main())
> I believe Guido suggested that idiom in his blog.

Ah, then I would suggest moving the code that requires proper cleanup
(the finally part) down a level, and simplify the top level so that 
all it does is catch all exceptions and convert to an error value
which it then returns.

Works out to about the same thing as saying "nest the try clauses"
but at least it has the advantage of higher cohesion in the two
separate code areas.


More information about the Python-list mailing list