Advanced topics Exceptions

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.

Throwing an Exception
if value == 0:
    throw ZeroDivisionError("division by zero")
Try and Catch
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:.

Finally
try:
    writer.writeLine("hello")
finally:
    writer.close()

Use finally for cleanup that must happen whether the protected code succeeds or not.

Try With Resource
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.

Declaring 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.

Practical Guidance
  • Throw typed exceptions with messages that explain the failure condition clearly.
  • Prefer resource-aware try syntax over manual cleanup when possible.
  • Do not use exceptions for ordinary branching that can be represented by normal control flow.