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

KATO Kanryu k.kanryu at gmail.com
Thu Aug 20 13:09:00 CEST 2009


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)
{
	try
	{
		var python_function =
Scope.GetVariable<IronPython.Runtime.PythonFunction>(funcName);
		var result = PythonEngine.Runtime.Operations.Call(python_function);
		return result;
	}
	catch (Microsoft.Scripting.SyntaxErrorException ex)
	{
		var Language = HostingHelpers.GetLanguageContext(PythonEngine);
		Console.WriteError(Language.FormatException(ex));
		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 &&
				method.DeclaringType.FullName.StartsWith("IronPython."))
			{
				continue;
			}

			result += FrameToString(frame) + Environment.NewLine;
		}
		Console.Info(result);

	}
	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}",
		frame.GetFileName(),
		lineNumber == 0 ? "unknown" : lineNumber.ToString(),
		methodName);
}
static string FrameToString(StackFrame frame)
{
	string stacks = string.Format(@"  File ""{0}"", line {1}, in {2}",
		frame.GetFileName(), frame.GetFileLineNumber(), frame.GetMethod().ToString());
	return stacks;
}



More information about the Ironpython-users mailing list