Skip to content

Commit 748c7ee

Browse files
committed
std::try теперь может сразу возвращать значение из catch
try(def() = parseInt("oops"), 42)
1 parent 0e2b92b commit 748c7ee

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

src/main/java/com/annimon/ownlang/modules/std/std_try.java

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,17 @@ public Value execute(Value... args) {
1414
try {
1515
return ((FunctionValue) args[0]).getValue().execute();
1616
} catch (Exception ex) {
17-
if (args.length == 2 && args[1].type() == Types.FUNCTION) {
18-
final String message = ex.getMessage();
19-
final Function catchFunction = ((FunctionValue) args[1]).getValue();
20-
return catchFunction.execute(
21-
new StringValue(ex.getClass().getName()),
22-
new StringValue(message == null ? "" : message));
17+
if (args.length == 2) {
18+
switch (args[1].type()) {
19+
case Types.FUNCTION:
20+
final String message = ex.getMessage();
21+
final Function catchFunction = ((FunctionValue) args[1]).getValue();
22+
return catchFunction.execute(
23+
new StringValue(ex.getClass().getName()),
24+
new StringValue(message == null ? "" : message));
25+
default:
26+
return args[1];
27+
}
2328
}
2429
return NumberValue.MINUS_ONE;
2530
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
use "std"
2+
3+
def testTryOnly() {
4+
assertEquals(1, try(def() = 1))
5+
assertEquals(-1, try(def() = parseInt("oops")))
6+
}
7+
8+
def testCatchFunction() {
9+
actual = try(def() = parseInt("oops"), def(class, cause) = class)
10+
assertEquals("java.lang.NumberFormatException", actual)
11+
}
12+
13+
def testCatchValue() {
14+
actual = try(def() = parseInt("oops"), 42)
15+
assertEquals(42, actual)
16+
}

0 commit comments

Comments
 (0)