Implement exception handling at interface level

Viewed 36

I have a simple interface:

public interface BatchProcessorInterface<I,O> {
    O process(I input);
}

Then, I have a lot of classes that implement this interface, 20+. My question is how can I implement exception handling (a try {} catch() {}), at the interface level? Is this doable? I don't see it as good code to put a try {} catch() {} block in each of the classes that implement the interface. Would an abstract class with method overloading be a better approach here?

Thank you!

1 Answers

You can create an abstract class with an abstract process(I input) method and safeProcess(I input) method which will have a try-catch block with process(I input) method call inside it:

public abstract class AbstractNumberParser {
    protected abstract int parseNumber(String numberString);

    public int parseNumberFromString(String numberString) {
        try {
            return parseNumber(numberString);
        } catch (NumberFormatException e) {
            System.err.println("Failed to parse number");
            return -1;
        }
    }
}

public class SimpleNumberParser extends AbstractNumberParser{
    @Override
    protected int parseNumber(String numberString) {
        return Integer.parseInt(numberString);
    }
}

AbstractNumberParser numberParser = new SimpleNumberParser();
System.out.println(numberParser.parseNumberFromString("15"));

I am not sure this is the best solution, but still an option to consider.

Related