如何处理"This exception is never thrown from the try statement body"



错误消息:此异常从未从try语句体中抛出。

这里展示了一个java程序:

class err1 extends Exception {}
class Obj1 {
    Obj1() throws err1 {
        throw new err1();
    }
}
class Main {
    public static void main(String[]argv) {
        Class a[] = {Obj1.class};
        try {
            a[0].newInstance();
        } catch(err1 e) { //Here meet my error
        }
    }
}

我该怎么办?不要告诉我将catch(err1 e)替换为catch(Exception e),因为我的Eclipse不知道可以抛出异常。

此外,当我推出它时,发生了以下事情。

Exception in thread "main" java.lang.Error:Unresolved compilation problem:
Unreachable catch block for err1. This exception is never thrown from the try statement body

然后我突然知道我该怎么做…

反射方法newInstance()抛出InstantiationException。如果在构造函数中遇到任何类型的异常,就会引发此异常。您需要抓住这一点,并在InstantiationException类中使用适当的方法抽象err1

newInstance()本身并不知道您的特定异常,而是将其封装在InstantiationException中。

编译时不知道Exception类型,因为class数组中可能包含任何内容。

你可以做的是检查捕获块中的类型:

public class Example {
    public static void main(String[] args) {
        Class a[] = {Obj1.class};
        try {
            a[0].newInstance();
        } catch (Exception e) {
            if(e instanceof CustomException) {
                System.out.println("CustomException");
            }
        }
    }
}
class Obj1 {
    Obj1() throws CustomException {
        throw new CustomException();
    }
}
class CustomException extends Exception {
}

忍不住要提到:如果你遵守公认的编码/命名/格式约定,这对其他人很有帮助。

最新更新