wlav / cppyy

Other
404 stars 42 forks source link

What is the expected behaviour when a C++ exception is uncaught? #237

Open srpgilles opened 4 months ago

srpgilles commented 4 months ago

Following code:

import cppyy

code = """
#include <exception>
throw std::domain_error("Exceptional");
"""

cppyy.cppexec(code)

fails with error:

compilation failed with unknown error

Same code when the exception is caught works without an hitch:

import cppyy

code = """
#include <exception>
#include <iostream>

try
{
    throw std::domain_error("Exceptional");
}
catch(const std::exception& e)
{
    std::cerr << e.what() << std::endl;
}
"""

cppyy.cppexec(code)
wlav commented 4 months ago

What platform/version of cppyy gives you the first error? I get a Python SyntaxError exception notifying me of compilation failed: Exceptional, which I'd figure is as expected.

srpgilles commented 4 months ago

My version of cppyy is Version: 3.1.2.

I run it on macOS, but a colleague on Ubuntu also got the issue (I will double check with him tomorrow).

Thanks for your reply!

VincentRouvreau commented 4 months ago

What seems strange is that the behaviour of throwing an exception with cppexec:

import cppyy

code = """
#include <exception>
throw std::domain_error("Exceptionnel");
"""

try:
    cppyy.cppexec(code)
except Exception as e:
  print(e)

that returns:

Failed to parse the given C++ code
compilation failed: Exceptionnel

seems different from what we have when throwing an exception in a function:

import cppyy

cppyy.cppdef("#include <exception>\nvoid exceptation() { throw std::domain_error(\"Exceptionnel\"); }")

try:
  cppyy.gbl.exceptation()
except Exception as e:
  print(e)

returns:

void ::exceptation() =>
    domain_error: Exceptionnel
wlav commented 4 months ago

Yes, b/c in the case of the former, the exception is caught by ROOT/meta, in the latter case, it's caught by CPyCppyy. Isn't for any particular reason, just legacy that makes it so that the Cling API isn't exposed directly.

I'll note that run-time access to Cling seems to becoming a more common use case of cppyy, as generating code snippets, ie. string manipulation, is more convenient in Python than C++. But that's not the original purpose of the package and so several of these utilities are under-developed. These use cases will be easier to support in cppyy 4.0, based on libinterop, as there the ROOT/meta layer is gone.