Raising exceptions when an exception is already present in Python 3

前端 未结 5 1675
感情败类
感情败类 2020-12-14 05:52

What happens to my first exception (A) when the second (B) is raised in the following code?

class A(Exception): pass
class B(Except         


        
5条回答
  •  無奈伤痛
    2020-12-14 06:49

    The 'causing' exception is available as c.__context__ in your last exception handler. Python is using this information to render a more useful traceback. Under Python 2.x the original exception would have been lost, this is for Python 3 only.

    Typically you would use this to throw a consistent exception while still keeping the original exception accessible (although it's pretty cool that it happens automatically from an exception handler, I didn't know that!):

    try:
        do_something_involving_http()
    except (URLError, socket.timeout) as ex:
        raise MyError('Network error') from ex
    

    More info (and some other pretty useful things you can do) here: http://docs.python.org/3.3/library/exceptions.html

提交回复
热议问题