// concurrent/CatchCompletableExceptions.java// (c)2017 MindView LLC: see Copyright.txt// We make no guarantees that this code is fit for any purpose.// Visit http://OnJava8.com for more book information.import java.util.concurrent.*;public class CatchCompletableExceptions {static void handleException(int failcount) {// Call the Function only if there's an// exception, must produce same type as came in:CompletableExceptions.test("exceptionally", failcount).exceptionally((ex) -> { // Functionif(ex == null)System.out.println("I don't get it yet");return new Breakable(ex.getMessage(), 0);}).thenAccept(str ->System.out.println("result: " + str));// Create a new result (recover):CompletableExceptions.test("handle", failcount).handle((result, fail) -> { // BiFunctionif(fail != null)return "Failure recovery object";elsereturn result + " is good";}).thenAccept(str ->System.out.println("result: " + str));// Do something but pass the same result through:CompletableExceptions.test("whenComplete", failcount).whenComplete((result, fail) -> { // BiConsumerif(fail != null)System.out.println("It failed");elseSystem.out.println(result + " OK");}).thenAccept(r ->System.out.println("result: " + r));}public static void main(String[] args) {System.out.println("**** Failure Mode ****");handleException(2);System.out.println("**** Success Mode ****");handleException(0);}}/* Output:**** Failure Mode ****Breakable_exceptionally [1]Throwing Exception for exceptionallyresult: Breakable_java.lang.RuntimeException:Breakable_exceptionally failed [0]Breakable_handle [1]Throwing Exception for handleresult: Failure recovery objectBreakable_whenComplete [1]Throwing Exception for whenCompleteIt failed**** Success Mode ****Breakable_exceptionally [-1]Breakable_exceptionally [-2]Breakable_exceptionally [-3]Breakable_exceptionally [-4]result: Breakable_exceptionally [-4]Breakable_handle [-1]Breakable_handle [-2]Breakable_handle [-3]Breakable_handle [-4]result: Breakable_handle [-4] is goodBreakable_whenComplete [-1]Breakable_whenComplete [-2]Breakable_whenComplete [-3]Breakable_whenComplete [-4]Breakable_whenComplete [-4] OKresult: Breakable_whenComplete [-4]*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。