Error, Panic, and Recover in Golang

seventech

Ega Prasetya

Posted on March 6, 2021

Error, Panic, and Recover in Golang

Ok so here we'll learn about use of error , besides we'll also learn about the use of Panic to set up Panic Error and Recover to cover it.

Using Error

error is a type which has one property of error()_ method. This method returns the details of the message error in the string and includes the type which contained the Nil.

Below is a simple program sample to detect ingestion from the user, whether numeric or not.

Alt Text

Result, if we type number and string:

Alt Text

Alt Text

The statement fmt.Scanln(&input) used to capture typed by the user before he hits the enter, then keeps it as a string to the input variable.

Next, those variables are converted to numerical types using strconv.Atoi(). The function returns the 2 data, contained by number and err.

Panic

Panic is used to display stack trace error while also halting flow goroutine ( because main() is goroutine, the same drag is also applied ).

Panic displayed an error message in the console, just like fmt.Println(). The information of error displayed is stack trace error, so it`s very detailed on hilarious.

Next, back to your code and changed in block condition else.

Alt Text

Result:

Alt Text

Recover

Recover useful to handle panic error, at the time of panic error Recover take over goroutine are panic (the panic message won`t appear).

Next, We add the catch() function, this function is a statement that he will revisit the panic error message that was supposed to appear.

Alt Text

Result:

Alt Text

Alt Text

Yeah, we done.

Follow me on:
Github
Instagram

💖 💪 🙅 🚩
seventech
Ega Prasetya

Posted on March 6, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related