在 catch 块中抛出相同的异常

Throwing same exception inside catch block

我有以下 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 块添加 'SuppressWarning',但在 snippet2 中,它显示为 throw 语句添加 'throws or try-catch' 块捕获块。

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

在片段 1 中,您不需要 return 语句。在 finally 块中 Java 已经知道处理完 finally 块后要做什么:要么继续异常处理,要么跳转到 finally 块之后的下一条语句。

所以在片段 1 中,只需将 return 语句移出 finally 块。

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 中,每个块中都会抛出一个异常。由于此异常不是未经检查的,因此必须在方法概要中指明。此外,没有 return 语句并且该方法的 return 值不是 void.

只需在方法末尾添加一个throws语句,用return语句。

public static void get() throws Exception {
    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;
    //      }
}

第二个代码段没有 return 值。它已被 finally 子句注释掉。

试试这个

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");
    }
    return 2;   // must return a value
//      finally{
//          System.out.println("In finally...");
//          return 2;
//      }

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