Home » Go Panic

Go Panic

Go panic is a mechanism by which we handle error situations. Panic can be used to abort a function execution. When a function calls panic, its execution stops and the control flows to the associated deferred function.

The caller of this function also gets terminated and caller’s deferred function gets executed (if present any). This process continues till the program terminates. Now the error condition is reported.

This termination sequences is called panicking and can be controlled by the built-in function recover.

Go Panic Example 1:

Output:

panic: Error Situation  goroutine 1 [running]: main.main() /Users/pro/GoglandProjects/Panic/panic example1.go:6 +0x39 

Go Panic Example 2

Output:

Calling x from main. Executing x... Calling y. Executing y.... Printing in y 0 Executing y.... Printing in y 1 Executing y.... Printing in y 2 Executing y.... Panicking! Defer in y 2 Defer in y 1 Defer in y 0 Recovered in x 3 Returned from x. 

Next TopicGo Concurrency

You may also like