Exceptions and Resource Safety
Klyn uses exceptions for exceptional failures, API boundary contracts, and resource cleanup.
This page covers throw, try, catch,
finally, and the language form that manages auto-closable resources.
if value == 0:
throw ZeroDivisionError("division by zero")
try:
riskyOperation()
catch e as Exception:
print(e.message)
A catch block may bind the exception to a local name with catch e as Exception:.
try:
writer.writeLine("hello")
finally:
writer.close()
Use finally for cleanup that must happen whether the protected code succeeds or not.
try resource = Resource():
resource.doWork()
finally:
print("resource is closed here")
The try resource = ...: form is the language-level resource-management construct.
It is the preferred pattern when the value implements AutoClosable.
throws
public class Parser:
public parse(value as String) as Int throws BadValueException:
throw BadValueException("invalid value")
Use throws when the API contract should make an exceptional path explicit.
- Throw typed exceptions with messages that explain the failure condition clearly.
- Prefer resource-aware
trysyntax over manual cleanup when possible. - Do not use exceptions for ordinary branching that can be represented by normal control flow.