Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

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

Open in new window


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);
    }
}

Open in new window


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
      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);
    }
}

Open in new window

Please advise
ASKER CERTIFIED SOLUTION
Avatar of Jeffrey Dake
Jeffrey Dake
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

when i pass argument while Run As Java application and arguments tab in eclipse i do see this behavior correctly between eating exception catch message and keeping catch message