Skip to content
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() {}) → nil
  • safeCall(func() { panic("boom") }) → the error panic: boom
  • safeCall(func() { panic(42) }) → the error panic: 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.

safecall.go — go
go · 8 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way