From 98c6a161b4e93ddc951c930be581e8285ade8370 Mon Sep 17 00:00:00 2001 From: luozhan Date: Thu, 22 Sep 2022 21:49:25 +0800 Subject: [PATCH] =?UTF-8?q?improve=20=E5=A4=84=E7=90=86sure=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E4=BC=9A=E6=8A=A5=E9=BB=84=E8=AD=A6=E5=91=8A=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...mbdaExceptionUtil.java => LambdaUtil.java} | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) rename com/robot/{LambdaExceptionUtil.java => LambdaUtil.java} (86%) diff --git a/com/robot/LambdaExceptionUtil.java b/com/robot/LambdaUtil.java similarity index 86% rename from com/robot/LambdaExceptionUtil.java rename to com/robot/LambdaUtil.java index 4b1b13c..9c4c3c4 100644 --- a/com/robot/LambdaExceptionUtil.java +++ b/com/robot/LambdaUtil.java @@ -6,9 +6,9 @@ * Lambda异常处理工具类 * * @author luozhan - * @create 2019-05 + * @date 2019-05 */ -public final class LambdaExceptionUtil { +public class LambdaUtil { @FunctionalInterface public interface ConsumerWithExceptions { @@ -54,9 +54,10 @@ public interface BiPredicateWithExceptions { /** * 包装普通函数(Function) *

- * 注:方法签名中的" throws E "编译器会提示多余,但其实是为了将具体的异常向外传递,如果不抛出的话: + * 注:方法签名中的" throws E "编译器会提示多余,但其实是为了将实际的异常向外传递,如果不这么做: * 1.外层代码中编译器将无法提示有异常需要处理 - * 2.也无法主动在外层捕获具体的异常,如果尝试try一个具体的异常,编译器将提示:在try语句体中永远不会抛出相应异常(Exception 'XXX' is never thrown in the corresponding try block) + * 2.也无法主动在外层捕获具体的异常,如果尝试try一个具体的异常,编译器将提示: + * 在try语句体中永远不会抛出相应异常(Exception 'XXX' is never thrown in the corresponding try block) */ public static Function wrapFunction(FunctionWithExceptions function) throws E { return t -> { @@ -164,12 +165,14 @@ public static void wrapRunnable(RunnableWithExceptions } /** - * 如果一个方法绝对不会抛出所申明的异常,可以使用该方法进行包装 + * 如果一段代码确保不会抛出所申明的异常,可以使用该方法进行包装 * 如:new String(byteArr, "UTF-8")申明了UnsupportedEncodingException, - * 但编码"UTF-8"是必定不会抛异常的,所以可以使用uncheck()进行包装 - * String text = uncheck(() -> new String(byteArr, "UTF-8")) + * 但编码"UTF-8"是必定不会抛异常的,使用sure进行包装 + * String text = sure(() -> new String(byteArr, "UTF-8")) + *

+ * 注: sure方法有一定的风险,因为它隐藏了可能的异常申明,所以请谨慎使用,确保(sure)不会抛出异常才可以使用 */ - public static R uncheck(SupplierWithExceptions supplier) { + public static R sure(SupplierWithExceptions supplier) { try { return supplier.get(); } catch (Exception exception) { @@ -180,11 +183,11 @@ public static R uncheck(SupplierWithExceptions su } @SuppressWarnings("unchecked") - private static void throwAsUnchecked(Exception exception) throws E { + private static void throwAsUnchecked(Exception exception) throws E { throw (E) exception; } - - private static class UnreachableException extends RuntimeException{ + + private static class UnreachableException extends RuntimeException { }