i'm trying to make a exception handler that takes different types of exception argugment, i declared a function type that takes any types that extends Throwable. It can compile when it's declared:
Function<? extends Throwable, Integer> handler = (IllegalStateException e) -> {
return 0;
};
but i could't pass throwable or any exception object to it and i don't understand why...
// cannot pass exception object
int result = handler.apply(new IllegalStateException("test"));
Anyone knows how to pass the argument correctly?
[jdk version]: 1.8
[error message]: i got 2 messages:
The method apply(capture#6-of ? extends Throwable) in the type Function<capture#6-of ? extends Throwable,Integer> is not applicable for the arguments (IllegalStateException)
Type mismatch: cannot convert from Function<capture#5-of ? extends Throwable,R> to Function<Throwable,R>
CodePudding user response:
i'm trying to make a exception handler that takes different types of exception argugment, i declared a function type that takes any types that extends Throwable
No, you haven't.
The function type you've declared:
Function<? extends Throwable, Integer> handler
says "this is a Function which accepts a specific subclass of Throwable
- but I don't know which".
You can't pass anything to handler.accept
, aside from literal null
, because the compiler doesn't know if the subclass of Throwable
you're passing is the right subclass of Throwable
.
For example, these are legal assignments:
Function<? extends Throwable, Integer> handler1 = (NullPointerException e) -> 0;
Function<? extends Throwable, Integer> handler2 = (IllegalStateException e) -> 0;
But those functions can only work correctly if they are passed a NullPointerException
and IllegalStateException
respectively. Given just handler1
and handler2
, the compiler has no information about which types are expected.
A generic function which accepts any kind of Throwable
would be:
Function<Throwable, Integer> handler
No need for bounds.
Don't forget that instances of all subtypes of Throwable
are also instances of Throwable
.
CodePudding user response:
Afterwards,
i found a way that can pass argument without compilation error
and it can work.
// the original one
Function<? extends Throwable, Integer> handler = (IllegalStateException e) -> {
System.out.println("handle IllegalStateException, msg: " e.getMessage());
return 0;
};
// cast it to one that accept specific type
// (instead of just a generic type upbound)
Function<Throwable, Integer> handler_ = (Function<Throwable, Integer>) handler;
// perform call on it
handler_.apply(new IllegalStateException("test"));
output:
handle IllegalStateException, msg: test
maybe it's solved now
while i'm not sure if there's other better solution...