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.
Result, if we type number and string:
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.
Result:
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.
Result:
Yeah, we done.
Top comments (0)