user8619111
user8619111

Reputation:

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'

Upvotes: 0

Views: 177

Answers (2)

Chaosfire
Chaosfire

Reputation: 6985

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"));

Upvotes: 0

dominicoder
dominicoder

Reputation: 10155

You're trying to throw a Class of type Exception instead of throwing an Exception. And what's the point of T? That's never used. Maybe you mean something like this:

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

Upvotes: -1

Related Questions