Reputation: 49
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.
Upvotes: 0
Views: 1478
Reputation: 3583
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+!
Upvotes: 1