gudii9
asked on
java empty catch block
Avoid Empty Catch Blocks
It’s a very bad habit to leave catch blocks empty, as when the exception is caught by the empty catch block, the program fails in silence, which makes debugging harder. Consider the following program which calculates sum of two numbers from command-line arguments:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Sum {
public static void main(String[] args) {
int a = 0;
int b = 0;
try {
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
}
int sum = a + b;
System.out.println("Sum = " + sum);
}
}
Note that the catch block is empty. If we run this program by the following command line:
1
java Sum 123 456y
It will fail silently:
1
Sum = 123
when i tried above example i am getting different error as below istead of getting 123
public class Sum {
public static void main(String[] args) {
int a = 0;
int b = 0;
try {
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
}
int sum = a + b;
System.out.println("Sum = " + sum);
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfB
at Sum.main(Sum.java:7)
https://www.codejava.net/coding/10-java-core-best-practices-every-java-programmer-should-know
even below good catch block example also gives same error
public class SumFixed {
public static void main(String[] args) {
int a = 0;
int b = 0;
try {
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
System.out.println("One of the arguments are not number." +
"Program exits.");
return;
}
int sum = a + b;
System.out.println("Sum = " + sum);
}
}
Please advise
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER