Return an arrayList as message in custom exception in JAVA

3.4k Views Asked by At

I need to output a List<String> when an exception is thrown. I want the program to stop its execution once the exception is thrown. To make things clear, my code has these two functions:

       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. 
        }

Whenever I throw the exception, the list is printed following the technical exception message which I do not want. Also, I cannot figure out a way to return using a getMessage() function implemented in my customException, in the throw statement as it gives a Expected throwable type error.

My Custom exception class looks like :

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

I am pretty new to this, any kind of help would be really appreciated. :)

3

There are 3 best solutions below

1
Sebphil On

Well here is one solution for such custom exception class:

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;
    }

}

You can use it as follows:

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);
}

Output:

[error#1, error#2, error#3]

But please note that this is not good practice in general. An exception should represent one error and not multiple ones. Normally you would create a base class, which represents a special "category" of your exceptions. Then specific errors can have their own exception that is derived from that base exception. One example is the FileNotFoundExcpetion (https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html), which is derived from IOException (which in turn is derived from the Exception class).

Throwing a string of multiple errors might indicate that your function is doing more than one thing (and these things might go wrong).

3
k_o_ On

You can do this by sub classing from RuntimeException (use a proper name and fields for the exception to make is self descriptive):

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 can only throw Throwables, no other objects. This is different from other programming languages. And the getMessage method which is used for a string representation is always returning a String. When you need a different behavior returning the real list you have to use you own interceptor / fault barrier reading the list of strings directly and apply a proper handling.

Can you be more precise when you need the list of string as List<String>. It seems you are using some handler code not only interested in the string message of the exception. In your code it seems that you are trying to return an Obj. Is your idea here to return an error list instead if it fails? This does not work that way. If you throw something then this will raise an exception and nothing is returned. This is a different program flow. If you want to return the list of errors you could also create a special

public class StatusResult {

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

// add constructor and getters here ...
}

But this kind of success / error handling is not Java like.

0
C Chaurasia On
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;
    }
}