std::try теперь может сразу возвращать значение из catch

try(def() = parseInt("oops"), 42)
This commit is contained in:
Victor 2019-01-04 22:57:07 +02:00
parent 0e2b92bfac
commit 748c7ee45e
2 changed files with 27 additions and 6 deletions

View File

@ -14,12 +14,17 @@ public final class std_try implements Function {
try { try {
return ((FunctionValue) args[0]).getValue().execute(); return ((FunctionValue) args[0]).getValue().execute();
} catch (Exception ex) { } catch (Exception ex) {
if (args.length == 2 && args[1].type() == Types.FUNCTION) { if (args.length == 2) {
switch (args[1].type()) {
case Types.FUNCTION:
final String message = ex.getMessage(); final String message = ex.getMessage();
final Function catchFunction = ((FunctionValue) args[1]).getValue(); final Function catchFunction = ((FunctionValue) args[1]).getValue();
return catchFunction.execute( return catchFunction.execute(
new StringValue(ex.getClass().getName()), new StringValue(ex.getClass().getName()),
new StringValue(message == null ? "" : message)); new StringValue(message == null ? "" : message));
default:
return args[1];
}
} }
return NumberValue.MINUS_ONE; return NumberValue.MINUS_ONE;
} }

View File

@ -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)
}