在某个try块,我有两个字符串变量,当我使用Integer.parseInt(string1)和Integer.parseInt(string2)时可能会导致NumberFormatException。问题是,如果我抓到一个异常,如何知道哪个字符串是麻烦制造者?我需要得到麻烦制造者的变量名。
这里是一些示例代码:
public class test {
public static void main(String[] args) {
try {
String string1 = "fdsa";
String string2 = "fbbbb";
Integer.parseInt(string1);
Integer.parseInt(string2);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
方法e.printStackTrace()不告诉我变量名;它只是告诉我的麻烦制造者的内容。
java.lang.NumberFormatException: For input string: “fdsa” at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580) at
java.lang.Integer.parseInt(Integer.java:615) at
test.main(test.java:9) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Process finished with exit code 0
我需要知道变量名称的原因是我需要提示用户发生了什么。例如,通过使用告诉用户string1是错误的
System.out.println(troubleMakerName + "is wrong!")
在我的要求中,用户应该输入
fd=(fileName,maxLength,minLength)
然后我将分析输入字符串并创建一些响应。所以我想检查maxLength和minLength是否会抛出NumberFormatException。在这种情况下,如果minLength有错误,那么我需要提示用户minLength是错误的。