Catch an exception in an inner try block so the outer catch does not fire.
← Control Flow · Ref: Q1156
Inner catch consumes the exception:
try try ex <- Exception("inner") throw ex catch -> e as Exception stdout.println("Inner handled") stdout.println("Outer continues") catch -> e as Exception stdout.println("Outer NOT reached")
Outer catch only fires if the exception is not caught by an inner block.
See Q1154 for basic try/catch. See Q1155 for finally.
Example
defines module qa.controlflow.nestedtrycatch defines program NestedTryCatchDemo() stdout <- Stdout() try stdout.println("Outer try: start") try stdout.println("Inner try: about to throw") ex <- Exception("Inner exception") throw ex catch -> e as Exception stdout.println("Inner catch: handled") stdout.println("Outer try: continues after inner block") catch -> e as Exception stdout.println("Outer catch: should not execute") stdout.println("Done")
Common mistakes
E01010 — EK9 has no 'new' keyword. Create the exception first, then throw it: ex <- Exception("msg") / throw ex.
Incorrect:
throw new Exception("msg")
Correct:
throw ex
Other ways to ask this
- I need nested error handling where the inner block consumes the exception
- In Java nested try-catch handles exceptions at the closest level. Show the EK9 pattern
- Given inner and outer try blocks, verify the inner catch prevents outer catch from running
- Handle an exception locally in a nested try without propagating to the outer block
Coming from another language?
Java: nested try-catch — same semantics. Python: nested try/except. EK9: nested try/catch — inner catch consumes the exception.
Keywords: outer, inner, catch, try, propagate, exception, nested