Exception Transparency
Neal Gafter
neal at gafter.com
Thu Feb 25 23:11:06 PST 2010
Exception Transparency, as it appears in BGGA and CfJ, would be a
valuable addition to project lambda. It can be usefully applied in
most applications of higher-order functions.
Take, for example, a lambda-enabled version of the Google Collections
filtering method:
<T> Iterable<T> filter(
Iterable<? extends T> input,
#bool(T) predicate)
{ ... }
or, using my preferred syntax
<T> Iterable<T> filter(
Iterable<? extends T> input,
(T)->bool predicate)
{ ... }
This method returns an iterable that includes only those elements from
the input iterable that pass the predicate.
Unfortunately, if your predicate includes any code that might throw a
checked exception (for example, looking up something in a database
where SqlException might be thrown as a result) you cannot simply use
this method. At best, you can write your predicate so that it catches
all checked exceptions and wraps them in unchecked exceptions. Then,
you had better remember to catch those unchecked exceptions in the
caller if you need to handle them; the compiler won't help you
remember to do so, as for checked exceptions. In short, the absence
of support for exception transparency in this API forces clients to
undermine the exception safety feature of the Java language. Without
language support for exception transparency, API authors have no
choice but to write their APIs this way.
If exception transparency were added to the lambda specification, this
method could be written this way:
<T,X extends Throwable> Iterable<T> filter(
Iterable<? extends T> input,
#bool(T)(throws X) predicate) throws X
{ ... }
or, using my preferred syntax
<T,X extends Throwable> Iterable<T> filter(
Iterable<? extends T> input,
(T throws X)->bool predicate) throws X
{ ... }
With this exception-transparent method, the caller can pass in a
lambda as a predicate that throws any checked exceptions. If any
exceptions are thrown by the predicate, they propagate out to the
caller of filter. And the language requires the compiler to diagnose
any uncaught checked exceptions at compile-time.
Without explicit language support, it is not practical to write APIs
that can act this way. If API authors cannot use function types to
write exception-transparent APIs, and clients of those APIs cannot use
checked exceptions, we have effectively deprecated checked exceptions.
I hope the project lambda specification is modified to include support
for exception transparency.
More information about the lambda-dev
mailing list