Java 8 Lambda function that throws exception?

后端 未结 26 1726
臣服心动
臣服心动 2020-11-22 03:14

I know how to create a reference to a method that has a String parameter and returns an int, it\'s:

Function         


        
26条回答
  •  无人及你
    2020-11-22 03:25

    You can use ET for this. ET is a small Java 8 library for exception conversion/translation.

    With ET it looks like this:

    // Do this once
    ExceptionTranslator et = ET.newConfiguration().done();
    
    ...
    
    // if your method returns something
    Function f = (t) -> et.withReturningTranslation(() -> myMethod(t));
    
    // if your method returns nothing
    Consumer c = (t) -> et.withTranslation(() -> myMethod(t));
    

    ExceptionTranslator instances are thread safe an can be shared by multiple components. You can configure more specific exception conversion rules (e.g. FooCheckedException -> BarRuntimeException) if you like. If no other rules are available, checked exceptions are automatically converted to RuntimeException.

    (Disclaimer: I am the author of ET)

提交回复
热议问题