2

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..

superevil
  • 56
  • 4
  • 2
    Replacing `throws Throwable` with `throws ClientNotFoundException` does not work? If not: please [edit] the post and include the compilation error. --- As an aside: `isExists(...)` is a terrible name. Renaming the method to `doesExist(...)` does not make it better; I would then expect the method to return a `boolean` instead of a `T`. – Turing85 Jan 02 '22 at 16:02
  • Edited! and sure, the name is a horrible option, it's just temporary – superevil Jan 02 '22 at 16:09
  • Obvious question - your exception class is subclassed (directly or indirectly) from Exception, right? – passer-by Jan 02 '22 at 16:37
  • Sure, it extends Exception – superevil Jan 02 '22 at 16:53
  • 1
    "unreported Exception"?? "must be caught or declared to be thrown" - are you handling the Exception (`catch` or `throws`) where the method is being called? – user16320675 Jan 02 '22 at 17:38
  • Oh no, I just need to throw it to the Controller – superevil Jan 03 '22 at 22:11
  • What version of Java are you using? This was fixed quite a while back, I believe: https://bugs.openjdk.org/browse/JDK-8054569. I can't reproduce your issue myself. – Matthew Read Dec 15 '22 at 23:26

0 Answers0