Java开发中如何将lambda表达式的异常抛出给上层调用方法?
问题原因
报错是因为lambda表达式实现的ResponseExtractor函数式接口的extractData方法未声明抛出受检异常,你在lambda内部直接抛出Exception这类受检异常不符合接口约定,因此编译器提示Unhandled exception type Exception。
解决方案
方案1:包装为运行时异常抛出
将捕获的受检异常包装为运行时异常抛出,运行时异常无需在接口方法预先声明,执行后再解包原始异常向上抛出即可:
private void bulkIndex(String filePath, RestTemplate restTemplate) throws Exception { RequestCallback requestCallback = request -> request .getHeaders(); ResponseExtractor<Void> responseExtractor = response -> { try { indexData(filePath); } catch (Exception e) { // 包装为运行时异常绕过lambda异常限制 throw new RuntimeException(e); } return null; }; try { restTemplate.execute(uri, HttpMethod.GET, requestCallback, responseExtractor); } catch (RuntimeException ex) { // 解包原始异常向上抛出 if (ex.getCause() instanceof Exception) { throw (Exception) ex.getCause(); } throw ex; } }
方案2:局部容器暂存异常,执行后统一抛出
如果不想做异常包装解包,可以用可变局部容器暂存异常,lambda内部不直接抛出,等execute执行结束后检查容器是否有异常,再直接向上抛出:
private void bulkIndex(String filePath, RestTemplate restTemplate) throws Exception { RequestCallback requestCallback = request -> request .getHeaders(); // 用数组作为可变容器存储捕获到的异常 final Exception[] exceptionHolder = new Exception[1]; ResponseExtractor<Void> responseExtractor = response -> { try { indexData(filePath); } catch (Exception e) { exceptionHolder[0] = e; } return null; }; restTemplate.execute(uri, HttpMethod.GET, requestCallback, responseExtractor); // 存在异常则直接向上抛出 if (exceptionHolder[0] != null) { throw exceptionHolder[0]; } }
两种方案都可以实现将原始异常传递到bulkIndex方法调用方的需求。
内容的提问来源于stack exchange,提问作者Mit94
相关产品推荐
相关产品推荐

