From 748c7ee45e427a97cdf98265f862aa38ead3fef4 Mon Sep 17 00:00:00 2001 From: Victor Date: Fri, 4 Jan 2019 22:57:07 +0200 Subject: [PATCH] =?UTF-8?q?std::try=20=D1=82=D0=B5=D0=BF=D0=B5=D1=80=D1=8C?= =?UTF-8?q?=20=D0=BC=D0=BE=D0=B6=D0=B5=D1=82=20=D1=81=D1=80=D0=B0=D0=B7?= =?UTF-8?q?=D1=83=20=D0=B2=D0=BE=D0=B7=D0=B2=D1=80=D0=B0=D1=89=D0=B0=D1=82?= =?UTF-8?q?=D1=8C=20=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=B8=D0=B7=20catch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit try(def() = parseInt("oops"), 42) --- .../annimon/ownlang/modules/std/std_try.java | 17 +++++++++++------ src/test/resources/modules/std/try.own | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) create mode 100644 src/test/resources/modules/std/try.own diff --git a/src/main/java/com/annimon/ownlang/modules/std/std_try.java b/src/main/java/com/annimon/ownlang/modules/std/std_try.java index c748b8f..4ae987b 100644 --- a/src/main/java/com/annimon/ownlang/modules/std/std_try.java +++ b/src/main/java/com/annimon/ownlang/modules/std/std_try.java @@ -14,12 +14,17 @@ public final class std_try implements Function { try { return ((FunctionValue) args[0]).getValue().execute(); } catch (Exception ex) { - if (args.length == 2 && args[1].type() == Types.FUNCTION) { - final String message = ex.getMessage(); - final Function catchFunction = ((FunctionValue) args[1]).getValue(); - return catchFunction.execute( - new StringValue(ex.getClass().getName()), - new StringValue(message == null ? "" : message)); + if (args.length == 2) { + switch (args[1].type()) { + case Types.FUNCTION: + final String message = ex.getMessage(); + final Function catchFunction = ((FunctionValue) args[1]).getValue(); + return catchFunction.execute( + new StringValue(ex.getClass().getName()), + new StringValue(message == null ? "" : message)); + default: + return args[1]; + } } return NumberValue.MINUS_ONE; } diff --git a/src/test/resources/modules/std/try.own b/src/test/resources/modules/std/try.own new file mode 100644 index 0000000..8a5ba12 --- /dev/null +++ b/src/test/resources/modules/std/try.own @@ -0,0 +1,16 @@ +use "std" + +def testTryOnly() { + assertEquals(1, try(def() = 1)) + assertEquals(-1, try(def() = parseInt("oops"))) +} + +def testCatchFunction() { + actual = try(def() = parseInt("oops"), def(class, cause) = class) + assertEquals("java.lang.NumberFormatException", actual) +} + +def testCatchValue() { + actual = try(def() = parseInt("oops"), 42) + assertEquals(42, actual) +} \ No newline at end of file