[IronPython] How to get stack traces from runtime exception with using generators.

Dino Viehland dinov at microsoft.com
Thu Aug 20 17:47:38 CEST 2009

Is there a reason you can't just call FormatException for both cases?  Depending on how the exception is propagated there may be more data in the exception Data property which we need to pick out and format to accurately display it.

-----Original Message-----
From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of KATO Kanryu
Sent: Thursday, August 20, 2009 4:09 AM
To: Discussion of IronPython
Subject: [IronPython] How to get stack traces from runtime exception with using generators.

I use generators in IronPython.
if a exception occars in the one, I cannot get correct stack traces.
How to get the trace?

The following, my codes.

/// <summary>
/// Run a python method, and if exception occars, to trap it.
/// </summary>
static object CallFunctionImp(callee func)
                var python_function =
                var result = PythonEngine.Runtime.Operations.Call(python_function);
                return result;
        catch (Microsoft.Scripting.SyntaxErrorException ex)
                var Language = HostingHelpers.GetLanguageContext(PythonEngine);
                Console.WriteError(FrameToString(new StackFrame(2, true)));
        catch (Exception ex)
                string type = ex.GetType().ToString();
                Console.Error("{0}: {1}\n", ex.GetType(), ex.Message);
                // write out call stacks
                Console.Info(FrameToString(new StackFrame(2, true)));

                // write out call stacks upper the function
                string result = "";
                foreach (DynamicStackFrame frame in ExceptionHelpers.GetStackFrames(ex, true))
                        MethodBase method = frame.GetMethod();
                        if (method.DeclaringType != null &&

                        result += FrameToString(frame) + Environment.NewLine;

        throw new MyScriptingExeption();
static string FrameToString(DynamicStackFrame frame)
        string methodName = frame.GetMethodName();
        int lineNumber = frame.GetFileLineNumber();

        return String.Format("  File \"{0}\", line {1}, in {2}",
                lineNumber == 0 ? "unknown" : lineNumber.ToString(),
static string FrameToString(StackFrame frame)
        string stacks = string.Format(@"  File ""{0}"", line {1}, in {2}",
                frame.GetFileName(), frame.GetFileLineNumber(), frame.GetMethod().ToString());
        return stacks;
Users mailing list
Users at lists.ironpython.com

More information about the Ironpython-users mailing list