java8常用的函数,以及lamda表达式有非运行异常能否在外部捕获

来源:互联网 发布:淘宝网正规催情药 编辑:程序博客网 时间:2024/06/05 05:41

Stream API中经常使用的函数式接口

函数式接口 参数类型 返回类型 描述 Supplier<T> 无 T 提供一个T类型的值 Consumer<T> T void 处理一个T类型的值 BiConsumer<T,U> T, U void 处理T类型和U类型的值 Predicate<T> T boolean 一个计算Boolean值的函数 ToIntFunction<T> T int 计算int值的函数 ToLongFunction<T> T long 计算long值的函数 ToDoubleFunction<T> T double 计算double的函数 IntFunction<R> int R 参数为int类型的函数(特别注意) LongFunction<R> long R 参数为long类型的函数 DoubleFunction<R> double R 参数类型为double的函数 Function<T,R> T R 一个参数类型为T的函数 BiFunction<T,U,R> T,U R 一个参数为T和U的函数 UnaryOperator<T> T T 对T进行一元操作 BinaryOperator<T> T,T T 对T进行二元操作

lamda常用的函数式接口

函数式接口 参数类型 返回类型 抽象方法名 描述 其他方法 Runnable 无 void run 执行一个没有参数和返回值的操作 Supplier<T> 无 T get 提供一个T类型的值 Consumer<T> T void accept 处理一个T类型的值 chain BiConsumer<T,U> T,U void accept 处理T类型和U类型的值 chain Function<T,R> T R apply 一个参数类型为T的函数 compose,andThen,identity BiFunction<T,U,R> T,U R apply 一个参数类型为T和U的函数值 andThen UnaryOperator<T> T T apply 对类型T进行的一元操作 compose,andThen,identity BinaryOperator<T> T,T T apply 对类型T进行的二元操作 andThen Predicate<T> T boolean test 一个计算boolean值的函数 And,or,negate,isEqual BiPredicate<T,U> T,U boolean test 一个含有两个参数,计算boolean的函数 and,or,negate

未声明抛出异常的表达式在使用的时候 只能在调用表达式的方法外捕获

假如有个方法的参数是个表达式
我们传入表达式的时候不能在调用这个方法的语句外直接try捕获

public static void testThrowExceptions() throws Exception {        int[] arr = new int[0];        arr[0] = 10;    }    public static void test(Runnable call) {        call.run();    }

不能写为

编译不过try {    test(() ->testThrowExceptions());} catch (Exception e) {}

而要写为

test(() -> {    try {        testThrowExceptions();    } catch (Exception e) {        e.printStackTrace();    }});

这个问题很小但是一定要搞清楚,我们这个表达式声明没有抛出异常
我们执行表达式的方法也没有处理或者抛出表达式可能发生的异常,因而我们调用test这个方法传入的表达式要自己处理异常。
Q:但是到底可以不可在test外部能不能接住表达式的异常的?
A:其实外部的try是可以捕获表达式内的语句的异常的。如果遇到必须在传入的表达式实现中处理异常,那只是编译的时候语法检查不过,要么是处理表达式的方法test没有抛出异常要么是没有处理异常

  • tips: 如何避免在表达式内写try-catch

①将public static void testThrowExceptions() throws Exception声明
改为

public static void testThrowExceptions() throws RuntimeException 或public static void testThrowExceptions()

这样避免在表达式内被强制处理非运行时异常,因为你的表达式内容没有显示的抛出非运行时异常。
②处理表达式的test方法声明抛出或者内部处理异常,或者表达式声明本身抛出异常
我们体验下,这样就能在外部捕获表达式内发生的异常了。

public static void test(Callable<String> call) throws Exception {    call.call();}public static void main(String args[]) {    try {        test(() -> {            testThrowExceptions();            return "ok";        });    } catch (Exception e) {             System.out.println("catche"+e);        e.printStackTrace();    }   }或者public static void testThrowExceptions() throws Exception {        int[] arr = new int[0];        arr[0] = 10;    }    public static void test(Callable<String> call) {        try {            call.call();        } catch (Exception e) {            e.printStackTrace();        }    }    public static void main(String args[]) {        test(() -> {            testThrowExceptions();            return "ok";        });    }
原创粉丝点击