diff --git a/program.own b/program.own index 5d8bb3c..83bacfe 100644 --- a/program.own +++ b/program.own @@ -252,4 +252,7 @@ println formatDate(d) println formatDate(d, newFormat("yyyy-MM-dd HH:mm:ss, EEEE")) println parseDate("2016/05/10", newFormat("yyyy/MM/dd")) println toTimestamp(d) -println newDate(toTimestamp(d) - 100000) \ No newline at end of file +println newDate(toTimestamp(d) - 100000) + +try(def() = try + 2) +println try(def() = try(), def(type, message) = sprintf("Error handled:\ntype: %s\nmessage: %s", type, message)) \ No newline at end of file diff --git a/src/com/annimon/ownlang/lib/modules/functions/std_try.java b/src/com/annimon/ownlang/lib/modules/functions/std_try.java new file mode 100644 index 0000000..b95f849 --- /dev/null +++ b/src/com/annimon/ownlang/lib/modules/functions/std_try.java @@ -0,0 +1,28 @@ +package com.annimon.ownlang.lib.modules.functions; + +import com.annimon.ownlang.exceptions.TypeException; +import com.annimon.ownlang.lib.*; + +public final class std_try implements Function { + + @Override + public Value execute(Value... args) { + Arguments.checkOrOr(1, 2, args.length); + if (args[0].type() != Types.FUNCTION) { + throw new TypeException(args[0].toString() + " is not a 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)); + } + return NumberValue.MINUS_ONE; + } + } + +} \ No newline at end of file diff --git a/src/com/annimon/ownlang/lib/modules/std.java b/src/com/annimon/ownlang/lib/modules/std.java index 952dc4a..2e5529d 100644 --- a/src/com/annimon/ownlang/lib/modules/std.java +++ b/src/com/annimon/ownlang/lib/modules/std.java @@ -22,6 +22,7 @@ public final class std implements Module { Functions.set("sleep", new std_sleep()); Functions.set("thread", new std_thread()); Functions.set("sync", new std_sync()); + Functions.set("try", new std_try()); // String Functions.set("sprintf", new std_sprintf());