【发布时间】:2021-08-30 15:13:03
【问题描述】:
我需要在抛出异常时输出List<String>。一旦抛出异常,我希望程序停止执行。
为了清楚起见,我的代码有以下两个功能:
List<String> exceptions = new ArrayList<>();
public Boolean validation(Obj obj){
if(condition1){ exceptions.add("exception1");}
if(condition2){ exceptions.add("exception2");}
.
.
.
if(exceptions.size() > 0) return false;
else return true;
}
public Obj getValidResponse(Obj obj){
if(validation(obj)){ return obj;}
else{ throw new CustomException(exceptions);} //on this line, the program should return the List<String> of all the exceptions stored.
}
每当我抛出异常时,列表都会在我不想要的技术异常消息之后打印。
此外,我无法在 throw 语句中找到使用 customException 中实现的getMessage() 函数返回的方法,因为它给出了Expected throwable type 错误。
我的自定义异常类看起来像:
public class CustomException extends RuntimeException{
public CustomException(List<String> s) {
super(String.valueOf(s));
}
}
我对此很陌生,任何形式的帮助都将不胜感激。 :)
【问题讨论】:
-
嗨,我不确定我是否理解正确,但似乎您想在抛出异常时向用户显示多个错误消息,即所有可能失败的验证消息的列表。如果是这种情况,您可以创建一个自定义对象,当抛出异常时您的异常会返回该对象。在该对象中,您可以有一个错误消息列表。
-
是的。我真正想要的是;每当函数'validation'返回false时,它应该抛出一个看起来像[“exception1”,“exception3”,“exceptionX”...]的异常。程序将终止。关于您的建议,我应该如何创建自定义对象?你能详细说明一下吗?谢谢
-
异常类必须扩展 Throwable,通常是 Exception 或 RuntimeException,而您的 CustomException 类似乎不是。请使用 CustomException 类的代码更新您的问题。
-
嗨@whbogado,我添加了我的CustomException。这个问题是,我仍然得到类似的结果 - 线程“main”中的异常 CustomException: ["exception1", "exception2", ....] 。有没有办法避免这种情况,只返回列表?
标签: java exception try-catch throws