Re: Identifying exceptions

Guido.van.Rossum@cwi.nl
Tue, 07 Mar 1995 13:48:35 +0100

> Let's presume I have the following piece of code:
>
> from socket import *
> from struct import *
>
> try:
> something_with_struct_and_sockets
> except: # Dilemma, how to catch only struct and socket exceptions?
> ...
>
> Now both struct and and socket have the error attribute. Because
> struct is imported after socket, its 'error' attribute overrides
> 'error' from socket.
>
> Possible solutions:
>
> A)
>
> from socket import *
> import struct
>
> try:
> something_with_struct_and_sockets
> except (error, struct.error), msg:
> print msg
>
> B)
>
> from socket import *
> SocketError = error
> from struct import *
> StructError = error
>
> try:
> something_with_struct_and_sockets
> except (SocketError,StructError), msg:
> print msg
>
>
> This is kind of hacky, but it works.
>
>
> Are there other, better solutions?

No, you figured out the best solutions.

<soapbox>
In general, you shouldn't be using "from module import *" except in
special cases. Your problem here is just one of the reasons why; in
general, using this feature means that it is hard to track (at least
for a human reader!) what is meant by a particular name. Exceptions
are those modules that are designed to be used in this way, e.g. the
module "stat" which defines constants like ST_MTIME.
</soapbox>

> ----------------------------------------------------------------------------
>
> The underlying problem is that if I use:
>
> from module import *
>
> or
>
> import * from module
>
> Then the generated exception is dependent on which import method
> was used. I'd like a module error to be 'module.error', independent
> of the import statements, but I'm not sure if this would clash with
> semantics of exceptions in general.

Well, the exception *object* is the same in all cases -- it's just
that the local name you have to use for it differs. With Python, an
object's name is a fairly superficial property -- it may have several
names, or none, and there generally isn't One True Name for every
object.

> Related question, is there a way to get exception's parameters
> without knowing which exception was raised?

Yes -- inside an except clause, use sys.exc_type and sys.exc_value.

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>