----- Original Message -----
> From: "-" <liangchenb...@gmail.com>
> To: "core-libs-dev" <core-libs-dev@openjdk.org>
> Sent: Sunday, May 21, 2023 6:52:44 AM
> Subject: Exposing checked exceptions that a MethodHandle can throw

> Hello,
> I am eliciting a discussion on the feasibility of tracking checked
> exceptions thrown by a MethodHandle. It is already requested in
> https://bugs.openjdk.org/browse/JDK-8268116 as it appears useful in
> the development of Foreign Function Interface API.

At the bytecode level, checked exceptions are stored in an attribute associated 
to a method.
  https://docs.oracle.com/javase/specs/jvms/se20/html/jvms-4.html#jvms-4.7.5

If you have a direct MethodHandle, you can already get the checked exceptions 
using Lookup.revealDirect() + MethodHandleInfo.reflectAs().

> 
> Currently, explicit MethodHandle usages are hampered by the catch
> block as the invoke methods are declared to throw any Throwable. Could
> it be possible that we specify the types of possible exceptions at
> MethodHandle invocation, so that:
> 1. Javac accepts code that just call the handle without ugly try-catch block
> 2. If the exceptions anticipated at invocation site are incompatible
> with (i.e. more specific than) those declared by the invoked handle,
> it can throw an exception like the existing `WrongMethodTypeException`
> eagerly.

The bug you reference seems to be about runtime information, but the paragraph 
above is about type-checking information.
The question here is "is the Java type system good enough to track checked 
exception in a backward compatible way ?"
Practically, I believe the answer is no, you can not compose function with 
different type parameters representing exception, there is no varargs of type 
parameters, there is no default type argument for a type parameter, etc.

It's also significant departure of the way the method handle API is created, 
the idea behind is that each combiner has the semantics of an existing 
bytecode. But all invoke* bytecodes are oblivious to exception. Said 
differently, the method handle API represent how the JVM works, not how Java 
the language works. 

> 
> Is such a plan feasible? Tracking of exceptions should be easy from
> Direct MH and the MethodHandles combinators already, while the
> invocation semantics update might be more complex, maybe in the form
> of compiler-inserted stubs before the actual invoke calls. I wish such
> improvements can make MethodHandle more friendly to direct usages in
> code, so users don't need to wrap MH invocations in try-catch blocks
> everywhere.

see above.

> 
> Chen Liang

RĂ©mi

Reply via email to