Exceptions thrown from c# iterators (yield) cannot be caught
Environment
- Pythonnet version: 2.3.0
- Python version: 2.7.10
- Operating System: Windows 7
Details
- Describe what you were trying to get done.
Catch an exception thrown from a C# iterator (done with yield return) in a python script.
- What commands did you run to trigger this issue? If you can provide a
Minimal, Complete, and Verifiable example
this will help us understand the issue.
using System; using System.Collections; using System.Collections.Generic; namespace Example { public class Script { public static IEnumerable<int> Test() { for (var i = 0; i < 10; i++) { if (i == 5) throw new Exception("Ooops!"); yield return i; } } } }
compile:
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe" /t:library bad_yield.csimport clr clr.AddReference(...) import System import Example try: for r in Example.Script.Test(): print r except System.Exception as e: print e.Message except Exception as e: print e.message except: print "Unfortunately this one doesn't work either"
- If there was a crash, please include the traceback here.
Unhandled Exception: System.Exception: Ooops! at Example.Script.<Test>d__13.MoveNext() in ... at Python.Runtime.Iterator.tp_iternext(IntPtr ob)