OOP - how to abort an __init__ when the initialisation code fails ?

Gregory Ewing greg.ewing at canterbury.ac.nz
Tue Nov 5 16:45:59 EST 2019


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

Often it makes sense to do both -- catch the exception and
re-raise it with a more informative error message, e.g.

      try:
          with open(filename, "w") as f:
              f.write("some")
              f.write("data")
      except OSError as e:
          raise OSError("Couldn't write fibble data to %s: %s" % (filename, e))

That way you don't get frustrating Microsoft style error
messages which say "The system could not open the specified file"
while giving no clue about *which* file was specified... aarggh!

-- 
Greg


More information about the Python-list mailing list