Stargaming
3/12/2008 1:01:00 PM
On Wed, 12 Mar 2008 01:05:06 +0100, Igor V. Rafienko wrote:
> Hi,
>
>
> I was wondering if someone could help me explain this situation:
>
> h[1] >>> import inspect
> h[1] >>> inspect.getmro(ValueError)
> (<type 'exceptions.ValueError'>, <type 'exceptions.StandardError'>,
> <type 'exceptions.Exception'>, <type 'exceptions.BaseException'>, <type
> 'object'>)
> h[2] >>> try:
> raise ValueError("argh")
> except object:
> print "why not?"
>
> Traceback (most recent call last):
> File "<stdin>", line 2, in <module>
> ValueError: argh
>
> The question is, why isn't ValueError caught? It *does* inherit from
> object (albeit indirectly), and my understanding of the wording of
> CPython docs is that this guarantees "compatibility" (between what is
> being raised and what is being caught).
I think inheritance is meant in reference to the Exception tree here. So,
the uppermost class is `BaseException`. Python 3 gives this exception
when trying to handle `object`::
TypeError: catching classes that do not inherit from BaseException is
not allowed
You are right, the wording is quite confusing here but that might be due
to the crude situation of exceptions: All old-style classes (deprecated
themselves) can be raised. Strings can still be raised but this is
deprecated. New-style classes can be raised but only if they inherit (at
least indirectly) from BaseException. I'd say: feel free to contribute
patches. :-)
> So, why doesn't object match ValueError (or any other exception for that
> matter). I am aware of "except:", but in my particular situation it is
> eh... unsuitable.
Why so?
The only possible solution me and my crystal ball could come up with is
that you're having a lot of old-style exceptions raised from some library
you cannot modify. You cannot handle any common base class and don't want
to handle every of the exceptions. If that's the case, just use a bare
`except` and utilize `sys.exc_info`.
HTH,