diff --git a/hutool-core/src/main/java/cn/hutool/core/lang/Opt.java b/hutool-core/src/main/java/cn/hutool/core/lang/Opt.java index ce96f742b..2cce3246e 100644 --- a/hutool-core/src/main/java/cn/hutool/core/lang/Opt.java +++ b/hutool-core/src/main/java/cn/hutool/core/lang/Opt.java @@ -32,6 +32,7 @@ import java.util.Objects; import java.util.Optional; import java.util.Collection; import java.util.NoSuchElementException; +import java.util.concurrent.Callable; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; @@ -43,7 +44,7 @@ import java.util.stream.Stream; * 详细见: * * @param 包裹里元素的类型 - * @author VampireAchao + * @author VampireAchao Cizai * @see java.util.Optional */ public class Opt { @@ -119,9 +120,9 @@ public class Opt { public static Opt ofTry(final SerSupplier supplier) { try { return Opt.ofNullable(supplier.getting()); - } catch (final Exception e) { + } catch (final Throwable e) { final Opt empty = new Opt<>(null); - empty.exception = e; + empty.throwable = e; return empty; } } @@ -143,7 +144,7 @@ public class Opt { * 包裹里实际的元素 */ private final T value; - private Exception exception; + private Throwable throwable; /** * {@code Opt}的构造函数 @@ -186,8 +187,8 @@ public class Opt { * @return 异常 * @since 5.7.17 */ - public Exception getException() { - return this.exception; + public Throwable getThrowable() { + return this.throwable; } /** @@ -198,7 +199,7 @@ public class Opt { * @since 5.7.17 */ public boolean isFail() { - return null != this.exception; + return null != this.throwable; } /** diff --git a/hutool-core/src/test/java/cn/hutool/core/lang/OptTest.java b/hutool-core/src/test/java/cn/hutool/core/lang/OptTest.java index f1542d46a..66baa5454 100644 --- a/hutool-core/src/test/java/cn/hutool/core/lang/OptTest.java +++ b/hutool-core/src/test/java/cn/hutool/core/lang/OptTest.java @@ -171,6 +171,10 @@ public class OptTest { // 你可以在里面写一长串调用链 list.get(0).getUser().getId() return list.get(0); }).exceptionOrElse("hutool"); + + Assert.assertTrue(Opt.ofTry(() -> { + throw new AssertionError(""); + }).getThrowable() instanceof AssertionError); Assert.assertEquals(npe, npeSituation); Assert.assertEquals(indexOut, indexOutSituation); Assert.assertEquals("hutool", npe); @@ -186,8 +190,8 @@ public class OptTest { } }); Assert.assertTrue( - (i % 2 == 0 && opt.getException() instanceof IllegalStateException) || - (i % 2 != 0 && opt.getException() instanceof NullPointerException) + (i % 2 == 0 && opt.getThrowable() instanceof IllegalStateException) || + (i % 2 != 0 && opt.getThrowable() instanceof NullPointerException) ); }); }