繁体   English   中英

在catch块中抛出相同的异常

[英]Throwing same exception inside catch block

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

以下是代码段:

摘录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中,它显示为catch块中的throw语句添加'throws或try-catch'块。

我详细研究了以下问题,但他们没有提供任何具体的理由。

第二个片段没有返回值。 它已被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;
//      }

在代码段1中,您不需要return语句。 在finally块中,一旦处理了finally块,Java就已经知道要做什么:要么继续异常处理,要么跳转到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语句的throws语句。

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;
    //      }
}

finally块应始终执行。 这是主要原因。 catch块中抛出异常,但在finally块掩码异常中执行return语句。 要么删除finally阻止或移动return陈述出的finally块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM