【发布时间】:2018-02-13 10:11:59
【问题描述】:
我正在向我的 Java 应用程序添加异常处理,但不明白为什么在某些情况下 Exception 方法返回的字符串 e.getMessage() 或 e.getLocalizedMessage() 包含我的自定义异常类的包.
这是我的配置方式:
MyCustomException:
package project.be.exception;
public class MyCustomException extends Exception{
public MyCustomException() {
}
public MyCustomException(String arg0) {
super(arg0);
}
public MyCustomException(Throwable arg0) {
super(arg0);
}
public MyCustomException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public MyCustomException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
super(arg0, arg1, arg2, arg3);
}
}
MyServiceCaller:
public class MyServiceCaller implements HISException DefaultRESTService<DefaultModel>{
public DefaultResponse get(Service_Api service, Object caller, Object param) throws MyCustomException {
try{
...
} catch (Exception e){
throw new MyCustomException ("Hello message exception");
}
}
}
MyBussinessClass:
...
try{
new MyServiceCaller().get(service, param1, param2);
} catch(MyCustomException e){
System.out.println(e.getLocalizedMessage());
}
...
控制台输出:
project.be.exception: Hello message exception
我想只打印消息而不打印之前的包裹。有什么建议吗?
编辑1:
使用 Exception.getMessage() 的输出是相同的,因此我放弃了可能的重复问题: Difference between e.getMessage() and e.getLocalizedMessage()
解决方案:
正如isaac 提到的,我将抛出的异常包装在另一个中,因此e.getMessage() 和e.getLocalizedMessage() 显示了包。
在我的情况下,解决输出很容易调用e.getCause().getMessage() 而不是e.getMessage() 和e.getLocalizedMessage()。
【问题讨论】:
-
@devpuh 与 e.getMessage() 相同的问题
-
缺少构造函数
MyCustomException的代码。你也覆盖getMessage()或getLocalizedMessage()吗? -
为什么不使用记录器而不是 sysout ?例如,java.util.logging。
-
@devpuh getMessage() 或 getLocalizedMessage() 未被覆盖
-
您可能会遇到here 中描述的问题,即您不知何故,无意中将抛出的异常包装在另一个异常中,特别是因为您说它只会“有时”发生。我认为如果你能提供一个工作和一个不工作的例子会很有帮助。