'Type Inference resolution procedure involving throws clause in Java
Consider the following article in JLS §18.1.3 - Bounds
Here when we try to identify the set of bounds on the inference variables - we have one of the following situations:
...
- throws α: The inference variable α appears in a throws clause.
...
A bound of the form throws α is purely informational: it directs resolution to optimize the instantiation of α so that, if possible, it is not a checked exception type.
I think this statement is incorrect:
- this is because ideally the throws clause is mentioned to take care of checked exceptions which can happen during the course of execution of the code.
- Then why still the JLS preventing α to be a Checked Exception?
- Ideally the inference variable α must be bounded to be an exception of Checked type rather than being an Unchecked variant.
Is my understanding correct here or am I missing something?
Solution 1:[1]
Consider this example:
public class Main {
public static void main(String[] args) {
foo(() -> System.out.println("Foo"));
}
public static <T extends Exception> void foo(ThrowingRunnable<T> runnable) throws T {
runnable.run();
}
}
interface ThrowingRunnable<T extends Exception> {
void run() throws T;
}
During the inference of the type parameter T when calling foo, there will be a "throws" bound on the type variable T, and T is inferred to be RuntimeException. If not for this bound, T would have been inferred as Exception because of the T extends Exception bound. This would have meant that I needed to do:
try {
foo(() -> System.out.println("Foo"));
catch (Exception e) {
// This won't be reached!
}
I had to handle the exception, even though all I'm doing in the lambda is printing things! That doesn't seem very nice, does it?
The purpose of this bound is so that if there's no reason for the method to throw a checked exception, it doesn't throw a checked exception, so that you don't have to write so many try...catches all over the place. foo would only throw a checked exception if you do things like:
foo(() -> new FileOutputStream("foo"));
If the effect of the bound were instead to force T to be a checked exception, it wouldn't be very useful at all.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
