Exception 捕获块避免编译错误?

Exception 捕获块避免编译错误?,exception,compiler-errors,try-catch,unreachable-code,Exception,Compiler Errors,Try Catch,Unreachable Code,我有以下代码,它给了我一个编译错误 //程序1——编译错误 但是在我添加了一些catch块之后,下面的代码就可以工作了 //程序2-无编译错误 //////////////////////////////////////////////////////////// 在“System.out.println(“Hi”);”处无法访问的代码 我想知道,添加不必要的catch块如何解决我的问题?因为在程序1中,编译器确信执行流永远不会到达“System.out.println(“Hi”);”行,因为既

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

//程序1——编译错误

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

//程序2-无编译错误

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

因为在程序1中,编译器确信执行流永远不会到达“System.out.println(“Hi”);”行,因为既没有要尝试的catch块,也没有某些条件 要抛出声明

您还可以通过使用variable to throw语句编写一些条件来避免此错误,如下所示

        int a =0;

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

当然,在program2中,catch块永远不会执行,但编译器假定有用于try-to-handle的特定catch,并将停止抛出错误。

欢迎使用StackOverflow!为了帮助您获得回答,请详细说明您希望回答的问题。您可以阅读有关如何提出最佳问题的信息。您缺少了最重要的信息-您得到的实际编译错误是什么,错误消息是什么?无法访问的代码位于“System.out.println”(“Hi”)
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");
    }
}
        int a =0;

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