[openstack-dev] [Review] Use of exception for non-exceptional cases
David Stanek
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:
>
> http://www.python.org/dev/peps/pep-3134/
>
> i.e. we can't do the right thing until Python 3, where we'd do:
>
> def download_image(host, port, path):
> try:
> 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):
try:
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
something like:
try:
do_something_that_raises_an_exception()
except:
exc_value, exc_tb = sys.exc_info()[1:]
raise MyException, exc_value, exc_tb
--
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek
www: http://dstanek.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.openstack.org/pipermail/openstack-dev/attachments/20130711/3abb8576/attachment.html>
More information about the OpenStack-dev
mailing list