-3

I have the following codes, and it is giving me a compilation error.

// Program1 -- Compilation error

public class ExceptionExample {
    public static void main(String[] a) {
        try {
            method();
        } catch (ClassCastException p) {} catch (Exception e) {
            System.out.println(" Exception");
        }
    }
    public static void method() {
        try {
            throw new NullPointerException();
        } finally {
            System.out.println("Hello");
        }
        System.out.println("Hi");
    }
}

But the following code works after I added some catch blocks.

// Program 2 - No Compilation error

public class ExceptionExample {
    public static void main(String[] a) {
        try {
            method();
        } catch (ClassCastException p) {

        } catch (Exception e) {
            System.out.println(" Exception");
        }
    }
    public static void method() {
        try {
            throw new NullPointerException();
        }

        // Below catch block has been added 
        catch (ClassCastException p) {

        }

        finally {
            System.out.println("Hello");
        }
        System.out.println("Hi");
    }
}

//////////////////////////////////////////////////////////// Unreachable code at "System.out.println("Hi");" I am wondering, how can adding unnecessary catch blocks solve my problem?

  • 3
    Welcome to StackOverflow! To help you get responses, please elaborate on the question that you would like answered. You can read [this](http://stackoverflow.com/help/how-to-ask) for information on how to ask the best questions. – ricky3350 Dec 17 '15 at 01:41
  • You're missing the most important information - what actual compilation error are you getting, what's the error message? – David Ferenczy Rogožan Dec 17 '15 at 02:22
  • Unreachable code at "System.out.println("Hi");" – prudhvi yallanki Dec 17 '15 at 17:46

1 Answers1

0

Because in the program1 the compiler is confident that the execution flow can never reach the line "System.out.println("Hi");" as there is neither catch block to try nor some condition to throw statement,

You can also avoid this error by writing some condition with variable to throw statement like this

        int a =0;

        if(a==0)
        throw new NullPointerException();

In the program2, of course the catch block never executes but compiler assumes that there is specific catch for try to handle and will stop throwing error.

Pradeep Charan
  • 653
  • 2
  • 7
  • 28