尽管陷入困境,仍会出现未处理的异常错误

时间:2012-10-16 20:33:19

标签: exception exception-handling

我为以下代码得到了一个未处理的异常类型错误,尽管如我所知,我已经在catch块中处理了异常。

class NewException extends Exception{
private String msg;
public NewException(String msg){
    this.msg = msg;
}
public String getExceptionMsg(){
    return msg;
}}
class CatchException {
public static void method () throws NewException{
    try {
        throw new NewException("New exception thrown");
    }
    catch (NewException e){
        e.printStackTrace();
        System.out.println(e.getExceptionMsg());
    }
    finally {
        System.out.println("In finally");
    }
}}
public class TestExceptions{
public static void main(String[] args){
    CatchException.method();
}}

1 个答案:

答案 0 :(得分:2)

您的method()声明它会引发NewException。无论内在的方法是什么都无关紧要:

public static void method () throws NewException{
    //...
}}

public static void main(String[] args){
    CatchException.method();
}}

编译器发现您在CatchException.method()中调用main()并且您没有以任何方式处理它(捕获或声明main()同时抛出NewException这样的错误。

编译器并不关心您是否实际抛出该异常。看看ByteArrayInputStream.close() - 它无法抛出IOException - 但是你声明它仍然需要处理它。