[openstack-dev] [Review] Use of exception for non-exceptional cases
dstanek at dstanek.com
Thu Jul 11 11:33:10 UTC 2013
On Thu, Jul 11, 2013 at 5:20 AM, Mark McLoughlin <markmc at redhat.com> wrote:
> But I think what you're saying is missing is the stack trace from the
> underlying exception.
> As I understood it, Python doesn't have a way of chaining exceptions
> like this but e.g. Java does. A little bit more poking right now shows
> up this:
> i.e. we can't do the right thing until Python 3, where we'd do:
> def download_image(host, port, path):
> s = socket.create_connection((host, port))
> except socket.error as e:
> raise ImageDownloadFailure(host, port, path, e.strerror) from e
> I haven't read the PEP in detail yet, though.
You can actually do this in Python 2 and keep the original context:
def download_image(host, port, path):
s = socket.create_connection((host, port))
except socket.error as e:
raise ImageDownloadFailure, e, sys.exc_info()[-1]
This will keep the original message and stack trace, but change the type.
You can also change the message if you want my mucking with e's message.
I've done that to add a string like " (socket.error)" at the end of the
exception message so I could see the original type.
If you really, really wanted to use a bare except you could also do
exc_value, exc_tb = sys.exc_info()[1:]
raise MyException, exc_value, exc_tb
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the OpenStack-dev