How do I reduce repetitive error handling in java

61 views Asked by At

So I have a code snippet similar to this. I feel like the if statements should be in a common function. I am not sure how to handle that because school and student should be passed to this function but they are of different types.

Teacher teacher = school.getTeachers();
if(ObjectUtils.isEmpty(teachers) {
    log.error(”cannot find teachers in school” + school.getSchoolName());
    throw new Exception(”xyz”);
} 
Student student = teacher.getStudents();
if(ObjectUtils.isEmpty(student)) {
    log.error(”cannot find students in school” + school.getSchoolName());
    throw new Exception(”xyz”);
2

There are 2 answers

2
Ali0102 On

One way is to consider this case (and similar ones) in your class design. You could use inheritance. Let's say Teacher and Student inherit from Person. This way the code will be easier to extend in case you need to consider some more common logics for both classes of Teacher/Student. Create your own exception handler taking the Person class. You could use Optional in Java to throw your exception. For your log message, you can use the class name

0
Christoph W. On

There a different ways of handling your case. First of all, you are right that Teacher and Student are different types or classes, but all classes in Java have the common superclass Object, see also Object class (Java SE 21 & JDK 21). So you can at least rely on the Object class for a common/generic solution.

If you want your logic to throw an exception based on your condition be encapsulated in a method, you can use this approach:

private void assertSchoolPropertyNotEmpty(Object schoolProperty, String propertyName, String schoolName) {
    if(ObjectUtils.isEmpty(schoolProperty)) {
        log.error(String.format("cannot find %s in school %s", propertyName, schoolName));
        throw new Exception("xyz");
    }
}