【问题标题】:Catch block avoid Compilation Error?捕获块避免编译错误?
【发布时间】:2016-03-23 08:52:02
【问题描述】:

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

// 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 块如何解决我的问题?

【问题讨论】:

  • 欢迎来到 StackOverflow!为了帮助您获得答复,请详细说明您希望回答的问题。您可以阅读this,了解如何提出最佳问题。
  • 您遗漏了最重要的信息 - 您得到了什么实际的编译错误,错误信息是什么?
  • “System.out.println("Hi");”处的代码无法访问

标签: exception compiler-errors try-catch unreachable-code


【解决方案1】:

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

你也可以通过写一些带有变量的条件来抛出这样的语句来避免这个错误

        int a =0;

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

在 program2 中,当然 catch 块永远不会执行,但编译器假定存在特定的 catch 供 try 处理并停止抛出错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-03
    • 2016-10-17
    • 2012-10-06
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多