1

能够标记对象的值 ofString.valueOf() 将包含在任何堆栈跟踪中是否有用。在下面的示例中,我使用了“跟踪”。未在堆栈跟踪点声明的变量将被导入。这将使调试变得更加容易,并且使编写易于调试的程序变得更加容易。

以下代码的示例堆栈跟踪:

java.lang.NullPointerException:
    at Test.main(Test.java:7) index=0, sum=3, obj=null


public class Test {
  Object obj;
  public void main(String[] args) trace obj {
    trace int sum = 0;
    for(trace int index = 0; index < args.length; index++) {
      sum += Integer.parseInt(args[index]);
      sum += obj.hashCode();//Will cause NullPointerException
    }
  }
}

来自:http: //jamesjava.blogspot.com/2005/04/extra-info-in-stack-traces.html

4

8 回答 8

1

很诱人,但我不认为这个特性需要在 Java 中使用新的关键字(并且该语言的复杂性要高得多)。

我发现 Throwable.printStackTrace 的使用通常足以快速指出需要我注意的问题。

于 2008-09-19T19:04:07.163 回答
1

这可能很有用,但我认为它会使代码混乱 - 大概当代码工作时,您会想要删除“跟踪”关键字;也许某种形式的元数据会更合适

然后总是有打印语句...

于 2008-09-19T03:45:56.723 回答
1

也许我没有抓住重点,但为什么不使用合适的日志框架(例如 Log4j)呢?然后,您可以使用嵌套/映射的诊断上下文(NDC / MDC)来输出变量值。

于 2009-06-22T08:23:07.537 回答
1

我更喜欢一种标准的(基于注释的)方式来描述程序员的空值意图(FindBugs,JSR 305)。我曾经考虑过不仅有行号,还有列号包含在异常消息中,因此在长链调用中,您可以更容易地看到哪个点运算符导致了 NPE。正如其他人在 StackOverflow 上的 NPE 相关问题中所述,在大多数情况下,您会通过尝试访问空对象上的字段/方法来获得 NPE。

于 2009-06-22T08:38:00.427 回答
0

Eh. Personally I don't think it would be that useful. If I'm running my code and hitting exceptions I can more easily set a breakpoint and step into the code and see what all of the variables are at that point and figure out where it's really breaking.

Using this trace method not only would I have to keep adding and removing keywords from in front of variables as I worked on different bugs but I don't think that it would be any real improvement over just adding good logging/debugging messaging (which is much easier to remove or disable when pushed to production).

于 2008-09-19T13:51:26.900 回答
0

是的,它可能非常有用。我自己经常做这种事情,但我通常只把它编译成非生产代码。

于 2008-09-19T03:48:27.467 回答
0

我喜欢的是异常的一个属性,它将是导致抛出的所有方法签名的字符串数组......而不必从异常文本中解析它。

于 2008-09-19T03:52:30.327 回答
0

Visual Studio C# 调试器的调用堆栈窗口包括一个堆栈跟踪,其中显示了所有参数值。

于 2008-09-19T04:02:29.867 回答