英文:
Getting variable name of the variable causing the error in try catch (Java)
问题
在Java中是否有可能返回变量名?
如果是这样的话,该如何实现?
(我正在使用IntelliJ Community Edition)
编辑:
下方的评论回答了错误所在的行。我从未意识到函数名所在的行实际上是针对 精确 行而不是函数的开头。
英文:
Is it possible to return the variable name in java?
If so, how do you do it?
(I am using IntelliJ Community Edition)
EDIT:
Comment below answered about the line of where the error is. I never realize that the function name line was actually for the exact line and not for the start of the function.
答案1
得分: 1
假设有这段代码:
public class Test{
public static void main(String[] args){
try{
throw new IllegalArgumentException();
}catch(IllegalArgumentException iae){
iae.printStackTrace(); //获取堆栈轨迹
}
String s=null;
System.exit(s.length()); //Boom
}
}
如果你使用 java Test
运行它,会得到以下输出:
java.lang.IllegalArgumentException
at Test.main(Test.java:4) //这里是行号
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:9) //这里是行号
如果你使用 java -XX:++ShowCodeDetailsInExceptionMessages Test
运行它,会得到以下输出:
java.lang.IllegalArgumentException
at Test.main(Test.java:4)
Exception in thread "main" java.lang.NullPointerException: 无法调用 "String.length()",因为 "<local1>" 为空
at Test.main(Test.java:9) //您可以得到行号和为空的内容,这里是一个没有名称的局部变量
如果你使用 javac -g Test.java
进行编译,然后运行它,你会得到更多的输出:
java.lang.IllegalArgumentException
at Test.main(Test.java:4)
Exception in thread "main" java.lang.NullPointerException: 无法调用 "String.length()",因为 "s" 为空
at Test.main(Test.java:9)
这并不适用于其他异常,但 NPE(NullPointerException,空指针异常)经常会被抛出。
注意:-XX:+ShowCodeDetailsInExceptionMessages
只在 Java 14+ 版本中起作用!
英文:
Suppose this code:
public class Test{
public static void main(String[] args){
try{
throw new IllegalArgumentException();
}catch(IllegalArgumentException iae){
iae.printStackTrace(); //Get stacktrace
}
String s=null;
System.exit(s.length()); //Boom
}
}
If you run it with java Test
, you get this output:
java.lang.IllegalArgumentException
at Test.main(Test.java:4) //Here, the line
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:9) //Here, the line
If you run it with java -XX:++ShowCodeDetailsInExceptionMessages Test
, you get this output:
java.lang.IllegalArgumentException
at Test.main(Test.java:4)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local1>" is null
at Test.main(Test.java:9) //You get the line and what is null, here a local with no name
If you compile with javac -g Test.java
, and run it, you even get more output:
java.lang.IllegalArgumentException
at Test.main(Test.java:4)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "s" is null
at Test.main(Test.java:9)
It doesn't work for other exceptions, but a NPE is thrown quite often.
-XX:+ShowCodeDetailsInExceptionMessages will only work in Java 14+!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论