diff --git a/src/runtime/Exceptions.cs b/src/runtime/Exceptions.cs
index c3ac889ed..e7d8f9f0e 100644
--- a/src/runtime/Exceptions.cs
+++ b/src/runtime/Exceptions.cs
@@ -77,14 +77,24 @@ internal static void Shutdown()
/// __getattr__ implementation, and thus dereferencing a NULL
/// pointer.
///
- internal static bool SetArgsAndCause(BorrowedReference ob, Exception e)
+ /// the message read by the refresh of an exception created from .NET,
+ /// which reports a message Python can't hold by returning false
+ internal static bool SetArgsAndCause(BorrowedReference ob, Exception e, string? message = null)
{
NewReference args;
- if (!string.IsNullOrEmpty(e.Message))
+ if (!string.IsNullOrEmpty(message ?? e.Message))
{
+ using var msg = Runtime.PyString_FromString(message ?? e.Message);
+ if (msg.IsNull())
+ {
+ if (message != null)
+ {
+ return false;
+ }
+ throw PythonException.ThrowLastAsClrException();
+ }
args = Runtime.PyTuple_New(1);
- using var msg = Runtime.PyString_FromString(e.Message);
- Runtime.PyTuple_SetItem(args.Borrow(), 0, msg.StealOrThrow());
+ Runtime.PyTuple_SetItem(args.Borrow(), 0, msg.Steal());
}
else
{
@@ -102,7 +112,16 @@ internal static bool SetArgsAndCause(BorrowedReference ob, Exception e)
if (e.InnerException != null)
{
// Note: For an AggregateException, InnerException is only the first of the InnerExceptions.
- using var cause = CLRObject.GetReference(e.InnerException);
+ // a generated inner exception keeps its Python object, when it has one in this runtime
+ // whose CLR wrapper is still alive: .NET may have collected the weak wrapper meanwhile
+ var peer = e.InnerException is IPythonDerivedType derived ? PythonDerivedType.GetPyObj(derived) : default;
+ var wrapper = peer.Ref != null && peer.Run == Runtime.GetRun()
+ ? ManagedType.GetManagedObject(peer.CheckRun())
+ : null;
+ using var cause = wrapper != null
+ ? ClassDerivedObject.ToPython((IPythonDerivedType)e.InnerException)
+ : CLRObject.GetReference(e.InnerException);
+ GC.KeepAlive(wrapper);
Runtime.PyException_SetCause(ob, cause.Steal());
}
diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs
index daeacfcd7..61e23336d 100644
--- a/src/runtime/Types/ClassDerived.cs
+++ b/src/runtime/Types/ClassDerived.cs
@@ -904,8 +904,8 @@ public static void InvokeSetProperty(IPythonDerivedType obj, string propertyN
public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, object[] args)
{
- var selfRef = GetPyObj(obj);
- if (selfRef.Ref == null)
+ var createdFromDotNet = GetPyObj(obj).Ref == null;
+ if (createdFromDotNet)
{
// this might happen when the object is created from .NET
using var _ = Py.GIL();
@@ -922,6 +922,49 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec
null,
obj,
args);
+
+ // the Python object of an exception created from .NET got its args and __cause__
+ // before the base constructor set its Message and InnerException
+ if (!createdFromDotNet || obj is not Exception exception)
+ {
+ return;
+ }
+ using var gil = Py.GIL();
+ // a strong reference while it's refreshed: the Python object starts with a weak one
+ using var pySelf = ClassDerivedObject.ToPython(obj);
+ // .NET construction doesn't run the Python __init__, which Python overrides of Message may rely on:
+ // read it without them, as when the Python object was created
+ var pyObj = GetPyObj(obj);
+ SetPyObj(obj, BorrowedReference.Null);
+ string message;
+ try
+ {
+ // a .NET Message may wait on another thread that runs Python code
+ using var threads = Py.AllowThreads();
+ message = exception.Message ?? string.Empty;
+ }
+ catch (Exception)
+ {
+ // the exception keeps the args it was created with
+ return;
+ }
+ finally
+ {
+ SetPyObj(obj, pyObj.CheckRun());
+ }
+
+ try
+ {
+ if (!Exceptions.SetArgsAndCause(pySelf.Borrow(), exception, message))
+ {
+ Exceptions.Clear();
+ }
+ }
+ catch (Exception)
+ {
+ // such as an inner exception whose Message throws: construction succeeds as when
+ // the exception was created, without a cause
+ }
}
public static void PyFinalize(IPythonDerivedType obj)
diff --git a/src/runtime/Types/ClrObject.cs b/src/runtime/Types/ClrObject.cs
index 98ceba8f4..f5c8c0136 100644
--- a/src/runtime/Types/ClrObject.cs
+++ b/src/runtime/Types/ClrObject.cs
@@ -20,7 +20,8 @@ internal sealed class CLRObject : ManagedType
static NewReference Create(object ob, BorrowedReference tp)
{
Debug.Assert(tp != null);
- var py = Runtime.PyType_GenericAlloc(tp, 0);
+ // freed when reading or converting an exception's Message throws
+ using var py = Runtime.PyType_GenericAlloc(tp, 0);
var self = new CLRObject(ob);
@@ -32,7 +33,7 @@ static NewReference Create(object ob, BorrowedReference tp)
// slot if wrapping a CLR exception
if (ob is Exception e) Exceptions.SetArgsAndCause(py.Borrow(), e);
- return py;
+ return py.Move();
}
CLRObject(object inst)
diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py
index 709ac0feb..c8b205932 100644
--- a/tests/test_exceptions.py
+++ b/tests/test_exceptions.py
@@ -711,3 +711,80 @@ def test_namespaced_exception_subclass_override_errors():
"inherited str outer KeyError 'inner'",
"two-level inherited str outer KeyError 'inner'",
]
+
+
+_NAMESPACED_EXCEPTION_FROM_DOTNET_SCRIPT = """
+from System import Activator, Array, Exception as ClrException, String, Type
+
+class CreatedError(ClrException):
+ __namespace__ = "Python.Test.DotNetCreatedExceptions"
+ def __init__(self):
+ pass
+
+class ChildCreatedError(CreatedError):
+ __namespace__ = "Python.Test.DotNetCreatedExceptions"
+ def __init__(self):
+ pass
+
+class DelayedError(ClrException):
+ __namespace__ = "Python.Test.DotNetCreatedExceptions"
+ @clr.clrmethod(None, [str])
+ def __init__(self, text):
+ self.text = text
+ def get_Message(self):
+ return self.text
+
+class CollectingError(ClrException):
+ __namespace__ = "Python.Test.DotNetCreatedExceptions"
+ def __init__(self):
+ pass
+ def get_Message(self):
+ GC.Collect()
+ GC.WaitForPendingFinalizers()
+ return "collected"
+
+def check(name, error):
+ cause = error.__cause__
+ print(name, error.Message, error.args, cause.Message if cause is not None else None,
+ error.InnerException.Message if error.InnerException is not None else None)
+
+inner = ClrException("inner")
+created = clr.GetClrType(CreatedError)
+check("activator", Activator.CreateInstance(created, Array[Object](["custom message", inner])))
+check("constructor info", created.GetConstructor(Array[Type]([String])).Invoke(Array[Object](["message only"])))
+check("parameterless", Activator.CreateInstance(created))
+check("child", Activator.CreateInstance(clr.GetClrType(ChildCreatedError), Array[Object](["child message", inner])))
+
+# .NET construction doesn't run __init__: the caller runs it after the constructor
+delayed = Activator.CreateInstance(clr.GetClrType(DelayedError), Array[Object](["base message"]))
+delayed.GetType().GetMethod("__init__").Invoke(delayed, Array[Object](["initialized"]))
+check("delayed", delayed)
+
+collecting = Activator.CreateInstance(clr.GetClrType(CollectingError), Array[Object](["collecting message"]))
+GC.Collect()
+GC.WaitForPendingFinalizers()
+print("collecting", Object.GetType(collecting).Name, collecting.Message, collecting.args)
+
+generated_inner = Activator.CreateInstance(created, Array[Object](["generated inner"]))
+generated_inner.tag = "tagged"
+outer = Activator.CreateInstance(created, Array[Object](["outer", generated_inner]))
+print("generated cause", outer.__cause__ is generated_inner, outer.__cause__.tag)
+"""
+
+
+@pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime")
+def test_namespaced_exception_subclass_created_from_dotnet():
+ """The args and __cause__ of a __namespace__ exception subclass constructed from .NET
+ match the Message and InnerException its base constructor set"""
+ output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_FROM_DOTNET_SCRIPT)
+
+ default = "Exception of type 'Python.Test.DotNetCreatedExceptions.CreatedError' was thrown."
+ assert output[-7:] == [
+ "activator custom message ('custom message',) inner inner",
+ "constructor info message only ('message only',) None None",
+ f"parameterless {default} ({default!r},) None None",
+ "child child message ('child message',) inner inner",
+ "delayed initialized ('base message',) None None",
+ "collecting CollectingError collected ('collecting message',)",
+ "generated cause True tagged",
+ ]