-
Notifications
You must be signed in to change notification settings - Fork 0
Error Handling
While you were reading, my dear friend, you may have noticed compile and runtime errors. While we can't do anything about the former, we actually can do something about the latter.
What if you know some code can cause a runtime error? For example:
var select = function(n, ...args) {
return args[n];
};
print(select(2));This will cause a runtime error:
runtime error: array index out of range: 2
--> file.wi:2 in select()
--> file.wi:5 in main function
But we can use a handy built-in function called try - it accepts a function as the first argument, and all the next arguments get passed as the function's parameters:
var select = function(n, ...args) {
return args[n];
};
var result = try(select, 2);
if (!result.ok) {
print("oops!");
} else {
print(result.value);
}try returns an object with fields ok, value, and error - pretty obvious what they do except error may be confusing, it's just an error message, what actually happened, if we were to print it:
var select = function(n, ...args) {
return args[n];
};
var result = try(select, 2);
if (!result.ok) {
print("oops! this happened:", result.error);
} else {
print(result.value);
}We'd get:
oops! this happened:
array index out of range: 2
We can also use try inside of the select, just wrap that dangerous code in a function:
var select = function(n, ...args) {
var result = null;
try(function() {
result = args[n];
});
return result;
};
print(select(2)); // null
print(select(2, 3, 4, 5)); // 5Of course, this is all examples, try catches any runtime error.
Next: Require