Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 46660fa

Browse files
committed
Add Runtime.CheckExceptionOccurred(...)
Helps refactor exceptions checks
1 parent 59733ea commit 46660fa

File tree

2 files changed

+22
-13
lines changed

2 files changed

+22
-13
lines changed

src/runtime/pytuple.cs

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,7 @@ public PyTuple(PyObject o)
5151
public PyTuple()
5252
{
5353
obj = Runtime.PyTuple_New(0);
54-
if (obj == IntPtr.Zero)
55-
{
56-
throw new PythonException();
57-
}
54+
Runtime.CheckExceptionOccurred();
5855
}
5956

6057

@@ -63,6 +60,9 @@ public PyTuple()
6360
/// </summary>
6461
/// <remarks>
6562
/// Creates a new PyTuple from an array of PyObject instances.
63+
/// <para />
64+
/// See caveats about PyTuple_SetItem:
65+
/// https://www.coursehero.com/file/p4j2ogg/important-exceptions-to-this-rule-PyTupleSetItem-and-PyListSetItem-These/
6666
/// </remarks>
6767
public PyTuple(PyObject[] items)
6868
{
@@ -72,11 +72,8 @@ public PyTuple(PyObject[] items)
7272
{
7373
IntPtr ptr = items[i].obj;
7474
Runtime.XIncref(ptr);
75-
int r = Runtime.PyTuple_SetItem(obj, i, ptr);
76-
if (r < 0)
77-
{
78-
throw new PythonException();
79-
}
75+
Runtime.PyTuple_SetItem(obj, i, ptr);
76+
Runtime.CheckExceptionOccurred();
8077
}
8178
}
8279

@@ -104,10 +101,7 @@ public static bool IsTupleType(PyObject value)
104101
public static PyTuple AsTuple(PyObject value)
105102
{
106103
IntPtr op = Runtime.PySequence_Tuple(value.obj);
107-
if (op == IntPtr.Zero)
108-
{
109-
throw new PythonException();
110-
}
104+
Runtime.CheckExceptionOccurred();
111105
return new PyTuple(op);
112106
}
113107
}

src/runtime/runtime.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,21 @@ internal static int AtExit()
384384
internal static IntPtr PyNone;
385385
internal static IntPtr Error;
386386

387+
/// <summary>
388+
/// Check if any Python Exceptions occurred.
389+
/// If any exist throw new PythonException.
390+
/// </summary>
391+
/// <remarks>
392+
/// Can be used instead of `obj == IntPtr.Zero` for example.
393+
/// </remarks>
394+
internal static void CheckExceptionOccurred()
395+
{
396+
if (PyErr_Occurred() != 0)
397+
{
398+
throw new PythonException();
399+
}
400+
}
401+
387402
internal static IntPtr GetBoundArgTuple(IntPtr obj, IntPtr args)
388403
{
389404
if (Runtime.PyObject_TYPE(args) != Runtime.PyTupleType)

0 commit comments

Comments
 (0)