java - 在 catch block 中抛出相同的异常

标签 java exception exception-handling try-catch

我有以下 2 个代码片段,我想知道是什么让 java 编译器(在带有 Java 7 的 Eclipse 中)显示第二个片段的错误,为什么不显示第一个片段。

以下是代码片段:

片段 1

public class TestTryCatch {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(get());
    }

    public static int get(){
        try{
            System.out.println("In try...");
            throw new Exception("SampleException");
        }catch(Exception e){
            System.out.println("In catch...");
            throw new Exception("NewException");
        }
        finally{
            System.out.println("In finally...");
            return 2;
        }
    }
}

片段 2

public class TestTryCatch {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(get());
    }

    public static int get(){
        try{
            System.out.println("In try...");
            throw new Exception("SampleException");
        }catch(Exception e){
            System.out.println("In catch...");
            throw new Exception("NewException");
        }
//      finally{
//          System.out.println("In finally...");
//          return 2;
//      }
    }
}

在 eclipse 中,snippet1 显示为 finally block 添加“SuppressWarning”,但在 snippet2 中,它显示为 catch block 中的 throw 语句添加“throws or try-catch” block 。

我详细查看了以下问题,但他们没有提供任何具体原因。

最佳答案

finally block 应该总是 执行。这是主要原因。在catch block 中抛出异常,但在finally block 中执行的return 语句屏蔽了异常。要么删除 finally block ,要么将 return 语句移出 finally block 。

关于java - 在 catch block 中抛出相同的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33799676/

相关文章:

java - 如何忽略 Java 中的异常

java - Spring微服务端到端测试

java - 资源包 MissingResourceException

java - 使用Java通过网络复制文件数据非常慢

iphone - 如何在 iPhone 上的 HTTP 连接失败时弹出警报?

java - 在测试中收到异常时调用自定义方法

java - 自动完成下拉菜单不起作用

python - Python 中的条件 except 语句

java - 在 Java 中总是抛出相同的异常实例

python - 调用 sys.exit() 和抛出异常的区别