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

Luciano Ramalho luciano at ramalho.org
Mon Nov 4 16:18:39 EST 2019


On Mon, Nov 4, 2019 at 5:52 PM R.Wieser <address at not.available> wrote:
> I was thinking of (the needed) wrapping of the "newObject = classObject()"
> line in such a try..except block (to capture the re-casted exception).   I
> take it that that that means that the full contents of the __init__ block
> are wrapped too.

Python is not Java (also the title of a great post, look for it).

In this context, what I mean by that quote is to say that Python never
forces you to wrap anything in try/except blocks. Sometimes there is
nothing your program can do to fix the issue, so let the exception run
its course and terminate the program.

The only reason to catch an exception prior to aborting is to provide
a better error message, or log something. But in many situations
aborting with a traceback is good enough, and it costs 0.

In addition, as Rob said, it is usually a bad idea to wrap several
lines of code in a single try/except block, because that makes it
difficult to be specific when handling the different exceptions that
may happen. You should strive to be as specific as possible in the
exceptions that you choose to handle, and that pretty much requires
wrapping few (often just one) line of code in a try/except block.

> > or b) your except condition is too broad.  Don't "except Exception".  Only
> > catch specific exceptions where you can provide benefit by doing do.
>
> And that means I have to study the "try ... except" methodology a bit more,
> as I've currently got only a fleeting knowledge to how it works (including
> which error classes it can selectivily catch/filter).

Yes, you totally should learn how try/except works in Python, and also
learn a bit of Python culture, "the way we do things around here" ;-).

It is considered totally OK to use exception handling as a control
flow mechanism in Python. The interpreter and the standard library
have many examples of exceptions that do not signal errors, but merely
that something happened. For example, at a low level, Python
iterators/generators (pretty much synonyms around here) raise
StopIteration to signal the iterating for loop that there are no more
items. So the for statement implementation swallows StopIteration and
cleanly ends the loop.

Another example: the built-in function hasattr(obj, name) is actually
implemented (in C) by calling getattr(obj, name) and returning True if
no exception is raised, or False if AttributeError is raised. That is
common Python style.

Cheers,

Luciano


>
> Regards,
> Rudy Wieser
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Luciano Ramalho
|  Author of Fluent Python (O'Reilly, 2015)
|     http://shop.oreilly.com/product/0636920032519.do
|  Technical Principal at ThoughtWorks
|  Twitter: @ramalhoorg


More information about the Python-list mailing list