Handling Panics with Golang's Recover

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Golang, recover is a built-in function that can be used to recover from a panic. This Challenge will test your ability to use recover to handle panics.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/ErrorHandlingGroup(["`Error Handling`"]) go/ErrorHandlingGroup -.-> go/recover("`Recover`") subgraph Lab Skills go/recover -.-> lab-15420{{"`Handling Panics with Golang's Recover`"}} end

Recover

The mayPanic function in the provided code will panic when called. Your task is to modify the main function to recover from the panic and print the error message.

Requirements

  • Use the recover function to handle the panic in the mayPanic function.
  • Print the error message when a panic occurs.

Example

$ go run recover.go
Recovered. Error:
a problem

Summary

In this Challenge, you learned how to use the recover function to handle panics in Golang. By using recover, you can prevent your program from crashing and continue executing code.

Other Go Tutorials you may like