Pax
Pax

Reputation: 32

Why this java code does not catch all the exceptions

I dont understand why this piece of code only throws a NullPointerException.

(There is System.getProperty("")code which throws a IllegalArgumentException and x=x/0;which throws a ArithmeticException: / by zero but at the first statement,exception is thrown and others are ignored except while loop)

public static void main(String[] a) {


        try {
            String current = System.getProperty(null);
            String current2 = System.getProperty("");
            int num=2;
            num=num/0;
            System.out.println(String.valueOf(num));
        }
        catch(Exception e){

           System.out.println(e.toString());

        }   

        int i = 0;
        while (i < 10) {
            i++;
            System.out.println(i);
        }

        /**/
    }

Why the code execution does not continue until all the expressions are evaluated and printed their exception?

The output is :

java.lang.NullPointerException: key can't be null
1
2
3
4
5
6
7
8
9
10

Upvotes: 0

Views: 103

Answers (2)

Kon
Kon

Reputation: 10810

That's not how exception handling works at all in Java. The throwing of an exception gets propagated to the first qualifying catch block in the call stack, in this case your catch Exception(..) block. After the block runs, execution resumes at the bottom of the catch.

It wouldn't make sense for execution to resume on the line following the line that throws the Exception. You would have no guarantee about object state and it would make debugging arguably more difficult. But you shouldn't be using exception handling as flow control anyways. See here for more info about that: http://c2.com/cgi/wiki?DontUseExceptionsForFlowControl

Upvotes: 1

farrellmr
farrellmr

Reputation: 1905

The code exits to the catch block when the first exception is thrown, and doesnt execute remaining code in the try block

Upvotes: 1

Related Questions