E4174

E4174#

Compiler diagnostic name: control_in_defer.

Invalid control flow inside defer.

The right-hand side of defer is cleanup code that runs when the surrounding scope exits. It cannot change how that surrounding scope exits. MoonBit rejects return, break, continue, raise, calls to functions that may raise, and async calls inside defer.

Erroneous example#

fn answer() -> Int {
  defer { return 42 }
  0
}

The return would try to exit the surrounding function from cleanup code, so it is rejected.

Suggestion#

Keep defer for cleanup with Unit-returning, non-raising, synchronous code. Perform control flow after the deferred cleanup has been registered.

fn answer() -> Int {
  defer println("leaving answer")
  42
}