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

Skip to content

Exceptions thrown from c# iterators (yield) cannot be caught #475

Closed
@sirwhinesalot

Description

@sirwhinesalot

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.

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.cs
import 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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions