[英]How to print diff Msg for same NumberFormatException on diff cause in JAVA?
How to print diff Msg for same NumberFormatException on diff cause in JAVA? 如何在JAVA的差异原因上为相同的NumberFormatException打印差异消息?
try {
int a=Integer.parseInt(aStr);
int b= Integer.parseInt(bStr);
}catch (NumberFormatException ex) {
if ex's cause is from int a;//ex.getCause()=a?
System.out.println("a is not a integer");
if ex's cause is from int b
System.out.println("b is not a integer");
}
try {
final int a = Integer.parseInt(aStr);
} catch (final NumberFormatException ex) {
System.out.println("a is not a integer");
}
try {
final int b = Integer.parseInt(bStr);
} catch (final Exception e) {
System.out.println("b is not a integer");
}
You can declare the variables in two different try catch... 您可以在两个不同的try catch中声明变量。
try {
int a=Integer.parseInt(aStr);
}catch (NumberFormatException ex) {
System.out.println("a is not a integer");
}
try{
int b= Integer.parseInt(bStr);
}catch (NumberFormatException ex) {
System.out.println("b is not a integer");
}
Instead of doing that you can keep you try block unchanged and in the catch block print the stack trace by doing this 除了这样做,您可以尝试不更改块,并在catch块中通过执行此操作来打印堆栈跟踪
ex.printStackTrace();
This will give you the line number where the exception occurred which will either be at variable a or b 这将为您提供发生异常的行号,该行号将在变量a或b处
好吧,它仍然提供了不错的消息,如果您想拥有两个捕获块
Another possibility. 另一种可能性。
Introduce a string variable before the try block: 在try块之前引入一个字符串变量:
String msg = "a is not an integer";
try {
// parse a
msg = "b is not an integer";
// parse b
} catch (...) { println(msg); }
The only alternative to two try catch block would be setting a marker 两个try catch块的唯一替代方法是设置标记
boolean aSet = false;
try{
int a = Integer.parseInt(aStr);
aSet = true;
int b = Integer.parseInt(bStr);
} catch (NumberFormatException ex) {
if (aset) {....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.