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. :)
Well here is one solution for such custom exception class:
You can use it as follows:
Output:
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).