Exercise · Functions as values · lesson 12 of 12
★ Exercise: a panic becomes an error
Write func safeCall(f func()) (err error). It calls f. When f panics, safeCall returns an error whose text is panic: <the panic value> — the value printed the way fmt.Println prints it. When there was no panic, safeCall returns nil.
safeCall(func() {})→nilsafeCall(func() { panic("boom") })→ the errorpanic: boomsafeCall(func() { panic(42) })→ the errorpanic: 42
Constraints: f is called exactly once; the panic value may be anything — a string, a number, an error, or Go's own panic such as an index out of range; after a recovered panic the next safeCall works as usual.
Do not add extra imports unless the task says so explicitly.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.