throw
You can throw errors as in JavaScript.
If you throw a string, it will be converted to an Error
for you.
It has to be a string literal though — throw a
won't work if a
happens to be a String.
throw "This code throws a fit!"
assert
Usually, you'll only need to throw an exception under certain conditions.
assert true forbid =? 0 1 || `throw` splits the line in two between the condition and the error. assert false throw "Custom error"
If an explicit throw
isn't given, the compiler tries to create a descriptive error message.
For example, when asserting the result of a function call, the error message will include the function called and its arguments.
except
You can save yourself from an exception with except
.
The error given to to catch
is by default , but you could also provide a name.
except try throw 'oh-no! || same as: || catch foo || foo catch _.message || `finally` is optional finally pass
Usually you only need to catch a certain type of exception.
A type on the caught exception means that the exception will not be caught unless it is of that type.
Omitting a variable name before the type makes it _
.
You can only provide one untyped catch
and it has to come at the end, much like the else
of a switch
.
except try throw new TypeError 'type-no-good catch r:RangeError r catch :TypeError _ catch some-other-error some-other-error
Usually you only need to catch errors in a few lines.
Code in else
happens after the code in try
but errors in it are not caught.
This helps you make clear which specific code is dangerous, moving everything else into else
.
except try || `try` is for dangerous code that throws errors! foo = 'success catch 'failure else || `else` is for using values defined in `try`. || If there are errors here, they won't be caught. foo
If there are any errors in try
, else
never runs.
You can read code as: try (something dangerous)... catch (these errors)... else (if nothing was caught)...
else
can use values defined in try
, but catch
can't. Why? Because catch
only runs if something went wrong when defining those values.