When should I use try/finally without catch in EK9?
← Control Flow · Ref: Q934
The finally block runs regardless of whether an exception occurs. Use try/finally without catch when you want cleanup but not error handling at that level.
TRY/FINALLY PATTERN
try doWork() finally cleanup() // Always runs
The exception propagates up to the caller. The finally block still executes before propagation.
TRY/CATCH/FINALLY
try doWork() catch -> ex as Exception logError(ex) finally cleanup() // Runs after catch too
Finally runs in all scenarios: normal completion, exception caught, or exception propagating.
WHEN TO OMIT CATCH
Omit catch when the current scope cannot meaningfully handle the error. Let exceptions propagate to a higher-level handler while still guaranteeing local cleanup.
See Q902 for try/catch syntax. See Q932 for single catch type. See Q935 for nested try/catch.
Example
defines module qa.controlflow.tryfinally defines function riskyCalculation() as pure -> x as Integer y as Integer <- rtn as Float: #^ x / #^ y defines program TryFinallyDemo() stdout <- Stdout() //try/finally without catch — cleanup guaranteed stdout.println("Starting work") try result <- riskyCalculation(20, 4) stdout.println(`Result: ${result}`) finally stdout.println("Cleanup done") //try/catch/finally — full pattern try second <- riskyCalculation(50, 10) stdout.println(`Second: ${second}`) catch -> ex as Exception stdout.println(`Handled: ${ex}`) finally stdout.println("All finished")
Other ways to ask this
- Does EK9 support try/finally without catch?
- How do I ensure cleanup code runs in EK9?
- What is the finally block for in EK9?
Coming from another language?
Java: try-finally for cleanup, try-with-resources preferred. Python: try/finally, context managers preferred. Rust: Drop trait, no try/finally. Go: defer for cleanup. EK9: try/finally with optional catch.
Keywords: resource, finally, try, cleanup, guarantee, propagate, exception