Java 如何在Lambda中抛出异常?

Java 如何在Lambda中抛出异常?,java,Java,如何在lambda中抛出异常,例如在可选的 try { foo.bar(baz).ifPresentOrElse(theBar -> { // A code inside here needs to throw a custom exception so the outside can handle it // It can't throw atm, and it is an unhandled exception here }, () -> {

如何在lambda中抛出异常,例如在可选的

try {
   foo.bar(baz).ifPresentOrElse(theBar -> { 
      // A code inside here needs to throw a custom exception so the outside can handle it
      // It can't throw atm, and it is an unhandled exception here
   }, () -> { response.set(notFound()); }
} catch(CustomException e) {
  somethingImportantWhenExceptionIsThrown();
}

尽管在您的问题中没有明确提到,但我将假设您打算从
ifpresentorese
抛出一个选中的异常

首先,您应该尝试理解为什么不能抛出异常。
消费者
界面与
可运行
一样,只有一个抽象方法,这使其成为
@功能界面
。从文件中:

请注意,可以使用创建功能接口的实例 lambda表达式、方法引用或构造函数引用

这是
消费者
界面的简化版本:

public interface Consumer<T> {

    void accept(T t); // <-- NO throws Exception
}

尽管在您的问题中没有明确提到,但我将假设您打算从
ifpresentorese
抛出一个选中的异常

首先,您应该尝试理解为什么不能抛出异常。
消费者
界面与
可运行
一样,只有一个抽象方法,这使其成为
@功能界面
。从文件中:

请注意,可以使用创建功能接口的实例 lambda表达式、方法引用或构造函数引用

这是
消费者
界面的简化版本:

public interface Consumer<T> {

    void accept(T t); // <-- NO throws Exception
}

解决方案是使用:

并将包装此函数的方法标注为
,如下所示:

@SneakyThrows
void method() {
   try {
       foo.bar(baz).ifPresentOrElse(theBar -> { 
          throw()
       }, () -> { response.set(notFound()); }
   } catch(CustomException e) {
      somethingImportantWhenExceptionIsThrown();
   }
}

解决方案是使用:

并将包装此函数的方法标注为
,如下所示:

@SneakyThrows
void method() {
   try {
       foo.bar(baz).ifPresentOrElse(theBar -> { 
          throw()
       }, () -> { response.set(notFound()); }
   } catch(CustomException e) {
      somethingImportantWhenExceptionIsThrown();
   }
}

为什么不使用?我的意思是我需要它从里面扔,用
bar
方法扔。为什么不使用?我的意思是我需要它从里面扔,用
bar
方法扔。4)使用@Quark提供的黑客,但如果你想使用Lombok,这取决于你。4)使用@Quark提供的黑客,但是,如果你想使用龙目山,这取决于你。