On 11/5/19 11:52 AM, Peter J. Holzer wrote:
On 2019-11-04 18:18:39 -0300, Luciano Ramalho wrote:
In addition, as Rob said, it is usually a bad idea to wrap several
lines of code in a single try/except block

I disagree with this. While it is sometimes useful to wrap a single
line, in my experience it rarely is. The scope of the try ... except
should be a unit from a semantic point of view. For example, if you
open a file and write some data to it, you could write:

     try:
         f = open("a.file", "w")
     except OSError as e:
         ... handle exception
     try:
         f.write("some")
     except OSError as e:
         ... handle exception
     try:
         f.write("data")
     except OSError as e:
         ... handle exception
     try:
         close(f)
     except OSError as e:
         ... handle exception

But not only is this hard to read and ugly as heck, what would be the
point?

Much better to write:

     try:
         with open("a.file", "w") as f:
             f.write("some")
             f.write("data")
     except OSError as e:
         ... handle exception

Or maybe don't catch it here at all but just let it bubble up until it
hits a level where dealing with it makes sense from the user's point of
view (who may not care about an individual file, but about the task they
instructed the program to perform).

         hp


I mean, you sort of want "the right amount of stuff" in a try block. Lines that may exhibit a common failure, that you want to route to a common exception handler go into the same try block (per your example above). Things that are going to raise unrelated errors for unrelated reasons should be in different try blocks. Code that should only execute if the try block was error-free, but that you expect to not be able to raise errors itself, should go into the else block.

Like most of programming, hard-and-fast rules turn out to be impossible. Reality has squishy edges.

--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to