返回一个arrayList作为JAVA自定义异常中的消息

问题描述

我需要在抛出异常时输出 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. 
        }

每当我抛出异常时,列表都会打印在我不想要的技术异常消息之后。 此外,我无法找到一种使用在我的 customException 中实现的 getMessage() 函数返回的方法,在 throw 语句中,因为它给出了 Expected throwable type 错误

我的自定义异常类如下:

public class CustomException extends RuntimeException{
    public CustomException(List<String> s) {
        super(String.valueOf(s));
    }
}

我对此很陌生,任何形式的帮助都将不胜感激。 :)

解决方法

您可以通过从 RuntimeException 进行子类化来做到这一点(使用适当的名称和字段来生成自描述的异常):

public class CustomException extends RuntimeException {

    private List<String> myStrings;

    public CustomException(List<String> s) {
        this.myString = s;
    }

    public List<String> getMyStrings() {
        return myStrings;
    }

    public String getMessage() {
        return String.join(",",myStrings);
    }
}

Java 只能抛出 Throwables,不能抛出其他对象。这与其他编程语言不同。用于字符串表示的 getMessage 方法总是返回一个 String。当您需要返回真实列表的不同行为时,您必须使用自己的拦截器 / 故障屏障直接读取字符串列表并应用适当的处理。

当您需要字符串列表为 List<String> 时,您能更精确吗?看来您正在使用一些处理程序代码,不仅对异常的字符串消息感兴趣。在您的代码中,您似乎正在尝试返回 Obj。如果失败,您的想法是返回错误列表吗?这不是那样工作的。如果你抛出一些东西,那么这将引发异常并且不会返回任何内容。这是一个不同的程序流程。如果你想返回错误列表,你也可以创建一个特殊的

public class StatusResult {

    private boolean error;
    
    private Obj sucessObj;
   
    private List<String> errorMsgs;

// add constructor and getters here ...
}

但是这种成功/错误处理不像 Java。

,

这是针对此类自定义异常类的一种解决方案:

DENOM_x

您可以按如下方式使用它:

public class CustomException extends Exception{

    private final List<String> errors;

    public CustomException(List<String> errors) {
        this.errors = errors;
    }

    @Override
    public String getMessage() {

        String msg = errors.stream()
                .collect(Collectors.joining(","[","]"));

        return msg;
    }

}

输出:

public static void main(String[] args) {

    try {
        errorFunc();
    } catch (CustomException exception) {
        System.out.println(exception.getMessage());
    }
}

public static void errorFunc() throws  CustomException {

    List<String> errors = new ArrayList<>();
    errors.add("error#1");
    errors.add("error#2");
    errors.add("error#3");

    throw new CustomException(errors);
}

但请注意,这通常不是好的做法。异常应该代表一个错误而不是多个错误。通常你会创建一个基类,它代表你的异常的一个特殊“类别”。然后特定的错误可以有自己的异常,该异常派生自该基本异常。一个例子是 FileNotFoundExcpetion (https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html),它派生自 IOException(而IOException 又派生自 Exception 类)。

抛出一串多个错误可能表明您的函数正在做不止一件事情(这些事情可能会出错)。

,
import java.util.ArrayList;
import java.util.List;
public class CustomException extends Exception{
    private List<String> exceptions;
    public CustomException(List<String> exp) {
        this.exceptions = exp;
    }   
    public List<String> getExceptions(){
        return exceptions;
    }
    public static void main(String[] args) {
    
        try {
            boolean result = getValidResponse();
        }catch(CustomException e) {
            List<String> msgs = e.getExceptions();
            for(String ss:msgs) {
                System.out.println(ss);
            }
        }
    }   
    static List<String> exps = new ArrayList<String>(); 
    public static boolean validation(boolean error){
        boolean result = false;
        if(error) {         
            exps.add("Error msg 1");
            exps.add("Error msg 2");            
        }else{
            result =  true;
        }        
        return result;
    }   
    public static boolean getValidResponse() throws CustomException{
        boolean r = false;
        validation(true);
        if(exps.size()>0) {
            throw new CustomException(exps);
        }
        return r;
    }
}