Java Reference
In-Depth Information
Throw an Exception from Within a Lambda Expression
A lambda expression can throw an exception. If it throws a checked exception, however,
then that exception must be compatible with the exception(s) listed in the
throws
clause of
the abstract method in the functional interface. For example, if a lambda expression throws
an
IOException
, then the abstract method in the functional interface must list
IOExcep-
tion
in a
throws
clause. This situation is demonstrated by the following program:
Because a call to
read( )
could result in an
IOException
, the
ioAction( )
method of the
functional interface
MyIOAction
must include
IOException
in a
throws
clause. Without
it, the program will not compile because the lambda expression will no longer be compat-
ible with
ioAction( )
. To prove this, simply remove the
throws
clause and try compiling
the program. As you will see, an error will result.
Ask the Expert
Q
:
Can a lambda expression use a parameter that is an array?