简介
java 8中引入了lambda表达式,lambda表达式可以让我们的代码更加简介,业务逻辑更加清晰,但是在lambda表达式中使用的Functional Interface并没有很好的处理异常,因为JDK提供的这些Functional Interface通常都是没有抛出异常的,这意味着需要我们自己手动来处理异常。
因为异常分为Unchecked Exception和checked Exception,我们分别来讨论。
处理Unchecked Exception
Unchecked exception也叫做RuntimeException,出现RuntimeException通常是因为我们的代码有问题。RuntimeException是不需要被捕获的。也就是说如果有RuntimeException,没有捕获也可以通过编译。
我们看一个例子:
List<Integer> integers = Arrays.asList(1,2,3,4,5);
integers.forEach(i -> System.out.println(1 / i));
这个例子是可以编译成功的,但是上面有一个问题,如果list中有一个0的话,就会抛出ArithmeticException。
虽然这个是一个Unchecked Exception,但是我们还是想处理一下:
  integers.forEach(i -> {
   try {
    System.out.println(1 / i);
   } catch (ArithmeticException e) {
    System.err.println(
      "Arithmetic Exception occured : " + e.getMessage());
   }
  });
上面的例子我们使用了try,catch来处理异常,简单但是破坏了lambda表达式的最佳实践。代码变得臃肿。
我们将try,catch移到一个wrapper方法中:
 static Consumer<Integer> lambdaWrapper(Consumer<Integer> consumer) {
  return i -> {
   try {
    consumer.accept(i);
   } catch (ArithmeticException e) {
    System.err.println(
      "Arithmetic Exception occured : " + e.getMessage());
   }
  };
 }
则原来的调用变成这样:
integers.forEach(lambdaWrapper(i -> System.out.println(1 / i)));
但是上面的wrapper固定了捕获ArithmeticException,我们再将其改编成一个更通用的类:
 static <T, E extends Exception> Consumer<T>
 consumerWrapperWithExceptionClass(Consumer<T> consumer, Class<E> clazz) {
  return i -> {
   try {
    consumer.accept(i);
   } catch (Exception ex) {
    try {
     E exCast = clazz.cast(ex);
     System.err.println(
       "Exception occured : " + exCast.getMessage());
    } catch (ClassCastException ccEx) {
     throw ex;
    }
   }
  };
 }
上面的类传入一个class,并将其cast到异常,如果能cast,则处理,否则抛出异常。
这样处理之后,我们这样调用:
integers.forEach(
    consumerWrapperWithExceptionClass(
      i -> System.out.println(1 / i),
      ArithmeticException.class));
处理checked Exception
checked Exception是必须要处理的异常,我们还是看个例子:
static void throwIOException(Integer integer) throws IOException {
}
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
integers.forEach(i -> throwIOException(i));
上面我们定义了一个方法抛出IOException,这是一个checked Exception,需要被处理,所以在下面的forEach中,程序会编译失败,因为没有处理相应的异常。
最简单的办法就是try,catch住,如下所示:
  integers.forEach(i -> {
   try {
    throwIOException(i);
   } catch (IOException e) {
    throw new RuntimeException(e);
   }
  });
当然,这样的做法的坏处我们在上面已经讲过了,同样的,我们可以定义一个新的wrapper方法:
 static <T> Consumer<T> consumerWrapper(
   ThrowingConsumer<T, Exception> throwingConsumer) {
  return i -> {
   try {
    throwingConsumer.accept(i);
   } catch (Exception ex) {
    throw new RuntimeException(ex);
   }
  };
 }
我们这样调用:
integers.forEach(consumerWrapper(i -> throwIOException(i)));
我们也可以封装一下异常:
static <T, E extends Exception> Consumer<T> consumerWrapperWithExceptionClass(
   ThrowingConsumer<T, E> throwingConsumer, Class<E> exceptionClass) {
  return i -> {
   try {
    throwingConsumer.accept(i);
   } catch (Exception ex) {
    try {
     E exCast = exceptionClass.cast(ex);
     System.err.println(
       "Exception occured : " + exCast.getMessage());
    } catch (ClassCastException ccEx) {
     throw new RuntimeException(ex);
    }
   }
  };
 }
然后这样调用:
integers.forEach(consumerWrapperWithExceptionClass(
i -> throwIOException(i), IOException.class));
总结
本文介绍了如何在lambda表达式中处理checked和unchecked异常,希望能给大家一些帮助。
补充知识:java8常用的函数,以及lamda表达式有非运行异常能否在外部捕获
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";
  });
 }
以上这篇java 8 lambda表达式中的异常处理操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持免费资源网。

