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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With