Exceptions and flow of control

Published

2023-07-31

Exceptions and flow of control

While it’s considered pythonic to use exceptions and to follow the rule of EAFP (“easier to ask for forgiveness than permission”), it is unwise to use exceptions for controlling the flow of program execution except within very narrow limits.

Here are some rules to follow:

  • Keep try and except blocks as small as possible.

  • Handle an exception in the most simple and direct way possible.

  • Avoid calling another function from within an except block which might send program flow away from the point where the exception was raised.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).