wlav / cppyy

Other
391 stars 40 forks source link

Python exception source location not available in C++ #106

Closed torokati44 closed 1 year ago

torokati44 commented 1 year ago

The PyException class contains no information about the source location (file:line) of the represented Python exception. It at least leaves the exception in the interpreter, so I can query it from Python later, but for some applications, having this in the C++ exception is essential.

See this snippet for demonstration (or possibly as a starting point for a future regression test):

import cppyy

cppyy.cppdef("""
#include <iostream>
#include <stdexcept>

class Foo {
    public:
        virtual void call() = 0;
        virtual ~Foo() {}
};

void call_foo(Foo* foo) {
    try {
        foo->call();
    } catch (std::exception& e) {
        std::cout << "Exception caught in C++:\\n----\\n" << e.what() << "\\n----\\n";
    }
}
""")

class Bar(cppyy.gbl.Foo):
    def call(self):
        raise RuntimeError("Ouch!")

bar = Bar()
try:
    cppyy.gbl.call_foo(bar)
except:
    print("Exception caught in Python:")
    print("----")
    import traceback
    traceback.print_exc()
    print("----")
wlav commented 1 year ago

Released with cppyy 2.4.2 and its dependencies. Again, thanks for the pull request.