# 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

```{literalinclude} /sources/error_codes/4174_error/top.mbt
:language: moonbit
```

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.

```{literalinclude} /sources/error_codes/4174_fixed/top.mbt
:language: moonbit
```
