【发布时间】:2012-09-05 19:39:57
【问题描述】:
我有一个单独的 JAR 库,其中包含一组引发自定义异常的方法,例如:
public String methodName() throws CustomException {
// code here
}
然后我将 JAR 添加到类路径并在源代码的 try 语句中引用库方法:
try {
DemoClass demoClass = new DemoClass ();
demoClass.methodName() // this should throw a CustomException if something occurs
} catch (CustomException e) {
// something here
}
上面的代码sn-p一直返回如下编译错误:
CustomException 不会在相应的 try 语句体中抛出
如果该方法在本地上下文中(未打包在 JAR 中),则代码可以工作。所以我的问题是,是否可以从 JAR 库中“抛出”自定义异常?
【问题讨论】:
-
您在 try 块中引用的类,是
java.lang.Class还是某个类的占位符? -
是占位符,示例已更新。
-
唯一的可能是代码中的 jar 中存在 DemoClass 一个,并且其中任何一个都有不会引发异常的 methodName()。
-
“编译错误”是指“执行 javac 时”还是“我的 IDE 这么说”?
-
Kai:使用 maven 构建