Read an Exception Message Safely

Easy ⏱ 8 min 80% acceptance ★★★★★ 4.6
Write error_text(func) that calls the zero-argument func() and returns the string 'ok' on success, or f'failed: {err}' when it raises — where err is the caught exception converted to its message text via str(). Practice binding the exception with as and using its printable form.

Examples

Example 1
Input
error_text(lambda: int('xyz'))
Output
"failed: invalid literal for int() with base 10: 'xyz'"
Explanation

str(err) yields the human-readable message.

Constraints

  • Catch Exception, bind it with as.
  • Success returns exactly 'ok'.

Topics

Exception Handlingexception object

Companies

WiproHCLTechIBM

Hints

Hint 1

except Exception as err binds the object.

Hint 2

f-strings call str() on the exception automatically.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.