-3

我有以下代码,它给了我一个编译错误。

// Program1 -- 编译错误

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

但是在我添加了一些 catch 块之后,下面的代码就可以工作了。

// 程序 2 - 无编译错误

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

///////////////////////////////////////// //////////“System.out.println("Hi ");”处的代码无法访问 我想知道,添加不必要的 catch 块如何解决我的问题?

4

1 回答 1

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.

于 2015-12-28T19:00:01.080 回答