javaexceptionthrows

How to pass differents Exceptions to a Java method?


So the idea is I have a bunch of methods separated in different 'repo' classes, each one of these can arise a personalized exception (all of them created by me, extending generic Java Exception). All these methods make a call to the same class, the controller.

As it is right now, each 'repo' class is in charge of arising the exception, but I want to delegate that task to the controller, so I created a method in the controller like:

public <T> T generic(String input, Class<? extends Exception> exception) throws Exception { ... }

, my idea is, taking whatever exception class comes to the controller and then elevate the corresponding error from here like:

public <T> T generic(String input, Class<? extends Exception> exception) throws Exception { 
    call(input).orElseThrow(() -> exception); 
}

, but i cannot make this work since my IDE is telling me: Cannot resolve symbol 'exception'


Solution

  • If you work with Class<? extends Exception> exception, you would need to instantiate exception using Reflection. The Supplier may be something like this for example:

    Supplier<Exception> supplier = () -> {
          try {
            return clazz.getDeclaredConstructor().newInstance();
          } catch (InstantiationException | InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
            throw new RuntimeException(e);
          }
        };
    call(input).orElseThrow(supplier); 
    

    That's error prone and cumbersome.

    I suggest changing your method to work with Supplier, instead of Class.

    public <T> T generic(String input, Supplier<? extends Exception> exceptionSupplier) throws Exception {
        call(input).orElseThrow(exceptionSupplier);
    }
    

    And provide the supplier when calling the method:

    generic("some input", () -> new CustomException("message"));