-
Notifications
You must be signed in to change notification settings - Fork 9
Exception handling
In .NET, exceptions are objects that represent an abnormal behaviour in the program during runtime. When an expression is thrown, it bubbles up the callstack until a guard is found. If there are no guards, the entire application will close with an error.
To throw N expression, the throw
keyword is used:
throw new InvalidOperationException "Something went wrong!"
LENS also has the fail
function that throws a basic Exception
:
fail "Error..."
To catch an exception, the code must be enclosed in a try
block:
try
Math::Sqrt (-1)
catch e:ArgumentException
print "Argument {0} is invalid!" e.Message
catch
print "oops..."
As the example above shows, the try
block may be followed by one or more catch
blocks that will be executed if an exception of the specified type happens to be thrown.
Exceptions of a more specific type must be handled before exceptions of a less specific ones. Therefore, the parameterless catch
clause (or one where the type is explicitly stated as Exception
must always be the last. A compile time error is issued if there are other catch
clauses defined afterwards.
If a catch
clause cannot handle the exception, it can be thrown back without losing the stacktrace:
try
doSomething ()
catch e:SomeException
if e.IsWarning then
print "oops: {0}" e.Message
else
throw
The finally
keyword denotes a block of code that must always be executed. Even if there was an unhandled exception in the try
section, the code inside finally
will be executed before the exception bubbles up the callstack. It is sometimes useful for releasing resources or otherwise cleaning up:
var res = new Resource ()
try
var data = res.GetValue "test"
print "the value is {0}" data
catch
print "could not get data!"
finally
res.Dispose ()