我正在创建一个测试记录器,其中将包含有关引发的任何异常的信息,以便可以使用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;
}
}
}
虽然第一种方法是更灵活(因为它可以包含其他自定义数据),这里有我的顾虑:
- 永保异常对象后长时间。
- 如果异常对象阻止大对象被垃圾收集,则使用大量内存。
- 异常在上下文访问时返回错误值。
Q1。上述问题是否有效? Q2302。异常对象通常会引用很多其他数据吗?
通常,异常对象不会引用大量数据。在执行日志代码的持续时间内,您应该保持您的异常对象。 –