Exceptions: Throw in C# and except in (Iron)Python?
Question: anybody have an idea how to achieve that.

Been looking for a solution and all I find are ways to 'throw in python and
catch in C#'.

Ideally I'd like to have a C# method and wrap all my py code in a try/except
block. When the C# method throws I'd like to have py except catch it.

Is it possible at all? My last attempt:

    
    
    ScriptEngine pyEngine = Python.CreateEngine(options);
    dynamic pyScope = pyEngine.CreateScope();
    
    Action<string> fire = (s) => { throw new Exception(); };
    pyScope.Fire = fire;
    
    // ... Load the script...
    compiled = source.Compile();
    compiled.Execute(pyScope);
    // ...
    
    // Somewhere else from a function called by the py script itself 
    void calledByPy()
    {
        m_pyscope.Fire("s");
    }
    

On the python side my script looks like:

    
    
    try:
        calledByPy()
    except System.Exception, e:
        print str(e)
    

I'd like to see that line `print str(e)` called.


Answer: I don't think the trouble is in your Python. I can't quite speak to all the
C#, since I am loading up C# assemblies in IronPython with `clr.AddReference`
rather than running an interpreter with `ScriptEngine`.

This sort of thing works fine:

    
    
    import clr
    import System
    clr.AddReference(project_path + '\\bin\\Debug')
    from Namespace import CSharpThing
    
    try:
        foo = CSharpThing.DoStuff()  # Multithreaded. Can throw an AggregateException.
    except System.AggregateException as ae:
        # I want more information than "One or more exceptions occurred"
        for e in ae.InnerExceptions:
            print(e)
        raise  # Rethrow the original exception, so I get a stack trace to it.
    

