Throwing custom exception from generic method - Java

Viewed 242

I'm using Spring Boot and Spring Data JPA, and i have a generic method that returns a generic type object and a custom exception that needs to be thrown from the generic method. Unfortunately, I get an error from the IDE suggesting that I should throw the generic Throwable instead of my custom exception. Whenever I try to throw my exception, I get a compilation error.

The generic method -> Gets one of three client types from the database, or throws an ClientNotFoundException stating that the client wasn't found in db:

    public static <T> T isExists(JpaRepository repository, int id, ClientType clientType) throws Throwable {
    T fromDB = (T) repository.findById(id).orElseThrow(() -> new ClientNotFoundException("Error getting info from dababase", Calendar.getInstance(), null, clientType));
    return fromDB;
}

What seems to be the problem? How can I throw my custom exception from my generic method? Thanks :)

edited: If I manually throw from method header ClientNotFoundException, the lines go red and the app is not compiling-

The compilation error that I get is:

java: unreported exception java.lang.Throwable; must be caught or declared to be thrown

IDE (using IntelliJ) suggests 3 options:

  • Convert exception to Throwable
  • Annotate with @SneakyThrows
  • try/catch

The suggestions are not the best for me, so I'd like to check other solutions..

0 Answers
Related