panic function.
Panic
panic is a built-in function that stops the normal execution of the current goroutine. When a function calls panic, the normal execution of the function stops immediately and the control is returned to the caller. This is repeated until the program exits with the panic message and stack trace.
We will discuss goroutines later in the course.
panic function:
panic in action:
Recover
It is possible to regain control of a panicking program using the built-inrecover function, along with the defer keyword.
handlePanic function. Then, we can call it using defer:
Use Cases
If so, then when should we usepanic?
There are two valid use cases for panic:
An unrecoverable error
This is a situation where the program cannot simply continue its execution. For example, reading a configuration file which is important to start the program. There is nothing else to do if the file read itself fails.Developer error
This is the most common situation. For example, dereferencing a pointer when the value isnil will cause a panic.
Use
panic sparingly and prefer explicit error handling for most scenarios.