Skip to content

Exception context issue #245

@slozier

Description

@slozier

The meaning of "handling an exception" in sys.exc_info changed in Python 3. It changed from (see https://docs.python.org/3/library/sys.html#sys.exc_info):

executing or having executed an except clause

to:

executing an except clause

Because of this change the tracebacks may return incorrect outputs, for example:

def test4():
    try:
        raise Exception(1)
    except:
        pass    
    raise Exception(2)

test4()

outputs (we should only see the Exception: 2 traceback):

Traceback (most recent call last):
  File "<stdin>", line 3, in test4
Exception: 1

During handing of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in test4
Exception: 2

Here are a few test cases which should all pass:

import sys

def test1():
    try:
        raise Exception
    except:
        pass
    assert sys.exc_info() == (None, None, None)

def test2():
    def gen():
        try:
            raise Exception
        except:
            exc_info = sys.exc_info()
            yield exc_info
            yield sys.exc_info()
        yield sys.exc_info()
    x = gen()
    exc_info = next(x)
    assert sys.exc_info() == (None, None, None)
    assert next(x) == exc_info
    assert next(x) == (None, None, None)

def test3():
    try:
        try:
            raise Exception(1)
        except:
            pass    
        raise Exception(2)
    except Exception as e:
        assert e.__context__ is None

test1()
test2()
test3()

Metadata

Metadata

Assignees

No one assigned

    Labels

    coreIssues relating to core functionality (e.g. syntax)

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions