Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a list of objects along with Exception

Tags:

java

My Java program has a method that returns a List. It populates the list using various SQL queries. In some cases, the data may be absent. In that case I've to throw an Exception. Since it is a list, list may contain valid data. Is it possible to get the list as well as catch the Exceptions?

public List<Student> getStudentInfo(){
    //Contains some static info like name, dob of a Student
    List<Student> students = getStudentStaticInfo();
    try{
        for (Student student: students){
            student.setTotalMarks(getStudentMark(student.getId()));
            ...
        }
    catch(FailedToFetchDataException e) {
        throw new Exception("Failed to fetch data");
    } finally {
        return students;
    }

}

In this case, the method returns the list of valid student information. But in case of an Exception, I'm not able to find out.

Is there a way to handle both, get the valid info as well as get the exceptional scenarios.

like image 208
Anju Avatar asked Dec 20 '22 01:12

Anju


1 Answers

Your method will stop as soon as the Exception is thrown, if not it will have to handle multiple exceptions. You can do this.

public List<Student> getStudentInfo(
                     BiConsumer<FailedToFetchDataException, Student> handleError) {
    //Contains some static info like name, dob of a Student
    List<Student> students = getStudentStaticInfo();
    for (Student student: students) {
        try{
            student.setTotalMarks(getStudentMark(student.getId()));
            ...
        } catch(FailedToFetchDataException e) {
            handleError.accept(e, student);
        }
    }
    return students;
}
like image 71
Peter Lawrey Avatar answered Dec 25 '22 22:12

Peter Lawrey