【发布时间】:2013-01-23 11:11:25
【问题描述】:
我正在创建一个测试记录器,其中将包含有关引发的任何异常的信息,以便可以使用 GUI 正确显示它们。
使用以下构造是否安全:
public class TestLogEntry {
public System.Exception Exception { get; private set; }
public TestLogEntry(/*...,*/ System.Exception exception = null) {
//...
Exception = exception;
}
}
或者以下会更好吗?
public class TestLogEntry {
public string StackTrace { get; private set; }
public System.Type ExceptionType { get; private set; }
public string ExceptionMessage { get; private set; }
public TestLogEntry(/*...,*/ System.Exception exception = null) {
//...
if (exception != null) {
StackTrace = exception.StackTrace;
ExceptionType = exception.GetType();
ExceptionMessage = exception.Message;
}
}
}
虽然第一种方法更灵活(因为它可以包含额外的自定义数据),但我担心的是:
- 长时间持有异常对象。
- 如果异常对象阻止大对象被垃圾回收,则使用大量内存。
- 脱离上下文访问时返回错误值的异常。
第一季度。上述担忧是否有效?
第二季度。异常对象通常会引用很多其他数据吗?
【问题讨论】:
-
通常异常对象不会引用大量数据。在日志记录代码执行期间,您应该可以保留异常对象。