Java 8 Lambda function that throws exception? -
i know how create reference method has string parameter , returns int, it's:
function<string, integer>
however, doesn't work if function throws exception, it's defined as:
integer mymethod(string s) throws ioexception
how define reference?
you'll need 1 of following.
if it's code, define own functional interface declares checked exception
@functionalinterface public interface checkedfunction<t, r> { r apply(t t) throws ioexception; }
and use it
void foo (checkedfunction f) { ... }
otherwise, wrap
integer mymethod(string s)
in method doesn't declare checked exception:public integer mywrappedmethod(string s) { try { return mymethod(s); } catch(ioexception e) { throw new uncheckedioexception(e); } }
and then
function<string, integer> f = (string t) -> mywrappedmethod(t);
or
function<string, integer> f = (string t) -> { try { return mymethod(t); } catch(ioexception e) { throw new uncheckedioexception(e); } };
Comments
Post a Comment