Skip to content

Commit ad5410a

Browse files
Keep the Python error when it was set without a value (#159)
An error set with a type but no value, as PyErr_SetNone does (CPython's own next() among others, before 3.12), made FetchCurrentOrNull throw a NullReferenceException while converting it, losing the Python error. The value now comes from normalizing the error when it is missing. Co-authored-by: quantconnect-kronos[bot] <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 300a692 commit ad5410a

2 files changed

Lines changed: 16 additions & 2 deletions

File tree

‎src/embed_tests/TestPythonException.cs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,19 @@ public void InnerIsEmptyWithNoCause()
113113
Assert.IsNull(ex.InnerException);
114114
}
115115

116+
[Test]
117+
public void TestErrorSetWithoutValue()
118+
{
119+
using var _ = Py.GIL();
120+
// what PyErr_SetNone does, as C extensions use it: the error's value stays NULL until it is normalized
121+
Runtime.Runtime.PyErr_SetObject(Exceptions.ValueError.Reference, BorrowedReference.Null);
122+
123+
var ex = Assert.Throws<PythonException>(() => PythonException.ThrowLastAsClrException());
124+
125+
Assert.AreEqual("ValueError", ex.Type.Name);
126+
Assert.IsTrue(Runtime.Runtime.PyErr_Occurred().IsNull);
127+
}
128+
116129
[Test]
117130
public void TestPythonExceptionFormat()
118131
{

‎src/runtime/PythonException.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,10 +111,11 @@ internal static PythonException FetchCurrentRaw()
111111

112112
try
113113
{
114-
var normalizedValue = new NewReference(value.Borrow());
114+
// an error set without a value, as PyErr_SetNone does, only gets one once normalized
115+
var normalizedValue = new NewReference(value.BorrowNullable(), canBeNull: true);
115116
Runtime.PyErr_NormalizeException(type: ref type, val: ref normalizedValue, tb: ref traceback);
116117

117-
return FromPyErr(typeRef: type.Borrow(), valRef: value.Borrow(), nValRef: normalizedValue.Borrow(), tbRef: traceback.BorrowNullable(), out dispatchInfo);
118+
return FromPyErr(typeRef: type.Borrow(), valRef: value.IsNull() ? normalizedValue.Borrow() : value.Borrow(), nValRef: normalizedValue.Borrow(), tbRef: traceback.BorrowNullable(), out dispatchInfo);
118119
}
119120
finally
120121
{

0 commit comments

Comments
 (0)