Can I nest try/catch blocks in EK9?
← Control Flow · Ref: Q935
Nested try/catch blocks work in EK9. An inner try/catch handles errors at a fine-grained level while the outer handler catches anything that escapes.
NESTED PATTERN
try //Outer work try //Inner work that might fail riskyStep() catch -> innerEx as Exception handleInner(innerEx) //Continue outer work after inner handled moreWork() catch -> outerEx as Exception handleOuter(outerEx)
If the inner catch handles the exception, execution continues in the outer try. If the inner catch re-throws or if an exception occurs outside the inner try, the outer catch handles it.
WHEN TO NEST
Nest when different operations need different error handling strategies. The inner handler deals with a specific failure while the outer provides a safety net.
See Q902 for try/catch basics. See Q932 for single catch type. See Q934 for try/finally.
Example
defines module qa.controlflow.nestedtry defines function parseInteger() as pure -> text as String <- rtn as Integer: Integer(text) defines program NestedTryCatchDemo() stdout <- Stdout() stderr <- Stderr() //First try/catch handles one operation try parsed <- parseInteger("42") stdout.println(`Parsed: ${parsed}`) catch -> firstEx as Exception stderr.println(`First parse failed: ${firstEx}`) //Second try/catch handles another operation try second <- parseInteger("99") stdout.println(`Second parse: ${second}`) catch -> secondEx as Exception stderr.println(`Second parse failed: ${secondEx}`) finally stdout.println("All operations complete")
Other ways to ask this
- How do nested exception handlers work in EK9?
- Can I put a try inside another try in EK9?
- How do I handle different errors at different levels in EK9?
Coming from another language?
Java: nested try/catch common for layered error handling. Python: nested try/except same pattern. Rust: nested match on Result values. Go: nested if err != nil checks. EK9: nested try/catch with -> syntax for exception parameter.
Keywords: nested, inner, layered, exception, catch, try, outer, handler