C# exception.ToString()上的OutOfMemory异常
下面是.NET应用程序的一些日志输出C# exception.ToString()上的OutOfMemory异常,c#,.net,exception,exception-handling,error-handling,C#,.net,Exception,Exception Handling,Error Handling,下面是.NET应用程序的一些日志输出 Error in MainFunction. Message: Exception of type 'System.OutOfMemoryException' was thrown. InnerException: StackTrace: at System.Text.StringBuilder.ToString() at System.Diagnostics.StackTrace.ToString(TraceFormat traceForma
Error in MainFunction.
Message: Exception of type 'System.OutOfMemoryException' was thrown.
InnerException:
StackTrace: at System.Text.StringBuilder.ToString()
at System.Diagnostics.StackTrace.ToString(TraceFormat traceFormat)
at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Exception.GetStackTrace(Boolean needFileInfo)
at System.Exception.ToString(Boolean needFileLineInfo)
at System.Exception.ToString()
[the rest of the trace is removed]
它对应于下面一行应用程序代码。以下内容位于catch块中,并将字符串返回给实际抛出的方法:
private void MainFunction()
{
...
try
{
string doc = CreateXMLDocument(); // <- Out of Memory throws here
}
catch (Exception ex)
{
CoreLogging("Error in MainFunction.", ex);
}
}
private string CreateXMLDocument()
{
try
{
//Some basic and well constrained XML document creation:
...
}
catch (Exception ex)
{
return "Exception message: " + ex.ToString(); // <- This is the last line of the trace
}
}
我该怎么看这个?显然,应该使用Exception.Message而不是Exception.ToString,但我仍然想理解这一点。做
位于System.Text.StringBuilder.ToString
位于System.Diagnostics.StackTrace.ToStringTraceFormat traceFormat
是否意味着CreateXMLDocument中异常的堆栈跟踪是由OutOfMemory引起的,非常庞大?我很想知道这是怎么发生的,因为CreateXMLDocument中肯定没有循环调用,这是我能想到的唯一可能导致巨大堆栈跟踪的东西
还有其他人遇到过类似的情况吗?我有点猜测: 1 CLR引发OutOfMemoryException。2您捕获此异常并调用.ToString 3 ToString尝试将内存分配给堆栈跟踪,但。。。没有内存,引发另一个OutOfMemoryException
在您的评论中,您说XML文档有几百KB,如果您的服务器运行在32位上,这可能是一个问题,因为LOH的碎片 这很可能是在转移注意力。如何加载XML文档?与您的问题无关,但是为什么要返回异常而不是将其返回?@asawyer XML文档实际上只是一个字符串,它是通过迭代一个非常小的集合来构造的,并且有边界约束来确保它不能迭代过大的集合。你在任何地方都使用递归吗?@kmark2-足够公平-它被捕获了因为catch块抛出另一个异常,但原始异常被吞没。仍然像是一种代码气味。