Retry only what can succeed
Repeat an operation while it reports a transient error, but stop on a fatal one. A medium embedded C problem (Error handling), run and graded in the browser.
medium · Error handling · error-handling · retry · function-pointers
A sensor read can fail with E_BUSY (try again soon) or a fatal error such as E_NODEV (nothing will fix that). Write with_retry(op, max_tries):
- call
op()up tomax_triestimes, - return
E_OKas soon as one call succeeds, - return immediately on any error other than
E_BUSY, without calling again, - if every try was
E_BUSY, returnE_BUSYafter the last one.
Starter code
int with_retry(int (*op)(void), int max_tries) {
return op();
}Example tests
Succeeds on the third try
run(E_BUSY, E_BUSY, E_OK, 3, 5);Expected output:
result=0 calls=3A fatal error stops at once
run(E_NODEV, E_OK, E_OK, 3, 5);Expected output:
result=2 calls=1Learn it first
- Error handling and fault strategy · Error codes, assertions, safe states and keeping evidence of what went wrong.
More Error handling problems
- Parse a byte, report why it failed · Return a status code and write the result only when parsing succeeded.
- Greenhouse: is the water arriving? · Judge each pump run and tell an empty tank from a broken sensor.