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?
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 {
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
ex.printStackTrace();
This will give you the line number where the exception occurred which will either be at variable a or b
well it provides nice message still if you want you can have two catch blocks
Another possibility.
Introduce a string variable before the try block:
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
boolean aSet = false;
try{
int a = Integer.parseInt(aStr);
aSet = true;
int b = Integer.parseInt(bStr);
} catch (NumberFormatException ex) {
if (aset) {....
精彩评论