Catch IronPython Exceptions from C#

Hello, I am trying to use Rhino.Runtime.PythonScript to execute Python code (that may raise exceptions) from C#. I having some difficulties catching the exceptions because the raised types are not derived from System.Exception (please see screenshots below). I was wondering how can I fix this? Thank you in advance!

Capture
Unable to catch the exception raised from IronPython.

That code does not structure a try/catch block around the ExecuteScript function, it only tries to trap the action of adding an event handler to button.Click. You would need to write a separate function with a try/catch block and have your click handler call this function.

static void ExecuteScriptSafe(Rhino.Runtime.PythonScript script, string text)
{
  try { script.ExecuteScript(text); }
  catch (Exception ex)
  {
    Rhino.RhinoApp.WriteLine(ex.Message);
  }
}

...
buttonRun.Click += (s,e) => ExecuteScriptSafe(script, editor.Text);

2 Likes

Hi Steve, thank you very very much for your help!