是否可以对外部JAR中的方法使用"throws"

S-K*_*-K' 5 java jar exception

我有一个单独的JAR库,其中包含一组抛出自定义异常的方法,例如:

public String methodName() throws CustomException {
    // code here
}
Run Code Online (Sandbox Code Playgroud)

然后我将JAR添加到类路径中,并在源代码中的try语句中引用库方法:

try {
    DemoClass demoClass = new DemoClass ();
    demoClass.methodName() // this should throw a CustomException if something occurs
} catch (CustomException e) {
    // something here
}
Run Code Online (Sandbox Code Playgroud)

上面的代码片段不断返回以下编译错误:

从不在相应的try语句的主体中抛出CustomException

如果方法在本地上下文中(未打包在JAR中)代码可以运行..那么我的问题是,是否可以从JAR库中"抛出"自定义异常?

Vik*_*dor 1

你的类是在 jar 中还是在本地上下文中并不重要,它总是会抛出异常。您应该检查您是否正在使用该类并调用您想要的方法,而不是其他同名的类和其他方法。

我的预感是ParseException,当java.text.ParseException实际抛出前者时,您会在代码中导入后者并尝试捕获它,这就是编译器所抱怨的。您可能想要检查出现 CustomException 的所有位置,并且尝试捕获正确的位置。org.apache.commons.cli.ParseExceptiondemoClass.methodName()