0

Came across this piece of code: -

public <T> T call(final Callable<T> callable) {
    try {
         return callable.call();
    } catch (Exception exception) {
         if (exception instanceof RuntimeException) {
             throw (RuntimeException) exception; // Line 6
         } else {
             throw new RuntimeException(exception); // Line 8
         }    
    }
}
  1. What is the need for doing a (RuntimeException) exception at line 6?
  2. What is the difference between the exceptions being thrown at line 6 v/s line 8. Aren't they doing the same thing?
Adi
  • 387
  • 3
  • 6
  • 14

1 Answers1

1

The code there is to transform a checked exception into a unchecked exception. In Java, checked exceptions have to be declared on a method with the throws keyword, while unchecked exceptions don't need to be declared on the method. Exception is the base class for all exceptions while RuntimeException (which is a subclass of Exception) is the base class for all unchecked exceptions.

The code on line 6 is to make the compiler happy. As Exception is a checked exception, by casting it to RuntimeException the compiler won't enforce the exception to be declared on the method with a throws. Line 8 wrapes the checked exception into a unchecked exception.

Augusto
  • 28,839
  • 5
  • 58
  • 88