Panic in Golang

In Go language, panic is just like an exception, it also arises at runtime. Or in other words, panic means an unexpected condition arises in your Go program due to which the execution of your program is terminated. Sometimes panic occurs at runtime when some specific situation arises like out-of-bounds array accesses, etc. as shown in Example 1 or sometimes it is deliberately thrown by the programmer to handle the worst-case scenario in the Go program with the help of panic() function as shown in Example 2.
The panic function is an inbuilt function which is defined under the builtin package of the Go language. This function terminates the flow of control and starts panicking.

Syntax:

func panic(v interface{})

It can receive any type of argument. When the panic occurs in the Go program the program terminates at runtime and in the output screen an error message as well as the stack trace till the point where the panic occurred is shown. Generally, in Go language when the panic occurs in the program, the program does not terminate immediately, it terminates when the go completes all the pending work of that program.
For Example, suppose a function A calls panic, then the execution of the function A is stopped and if any deferred functions are available in A, then they are executed normally after that the function A return to its caller and to the caller A behaves like a call to panic. This process continues until all the functions in the current goroutine are returned, after that the program crashes as shown in example 3.



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Simple Go program which illustrates
// the concept of panic
package main
  
import "fmt"
  
// Main function
func main() {
  
    // Creating an array of string type
    // Using var keyword
    var myarr [3]string
  
    // Elements are assigned
    // using an index
    myarr[0] = "GFG"
    myarr[1] = "GeeksforGeeks"
    myarr[2] = "Geek"
  
    // Accessing the elements
    // of the array
    // Using index value
    fmt.Println("Elements of Array:")
    fmt.Println("Element 1: ", myarr[0])
  
    // Program panics because
    // the size of the array is
    // 3 and we try to access
    // index 5 which is not 
    // available in the current array,
    // So, it gives an runtime error
    fmt.Println("Element 2: ", myarr[5])
  
}

chevron_right


Output:

./prog.go:32:34: invalid array index 5 (out of bounds for 3-element array)

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program which illustrates 
// how to create your own panic
// Using panic function
package main
  
import "fmt"
  
// Function
func entry(lang *string, aname *string) {
  
    // When the value of lang 
    // is nil it will panic
    if lang == nil {
        panic("Error: Language cannot be nil")
    }
      
    // When the value of aname
    // is nil it will panic
    if aname == nil {
        panic("Error: Author name cannot be nil")
    }
  
    // When the values of the lang and aname 
    // are non-nil values it will print 
    // normal output
    fmt.Printf("Author Language: %s \n Author Name: %s\n", *lang, *aname)
}
  
// Main function
func main() {
  
    A_lang := "GO Language"
  
    // Here in entry function, we pass 
    // a non-nil and nil values
    // Due to nil value this method panics
    entry(&A_lang, nil)
}

chevron_right


Output:

panic: Error: Author name cannot be nil

goroutine 1 [running]:
main.entry(0x41a788, 0x0)
    /tmp/sandbox108627012/prog.go:20 +0x140
main.main()
    /tmp/sandbox108627012/prog.go:37 +0x40

Example 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program which illustrates the
// concept of Defer while panicking
package main
  
import (
    "fmt"
)
  
// Function
func entry(lang *string, aname *string) {
  
    // Defer statement
    defer fmt.Println("Defer statement in the entry function")
  
    // When the value of lang
    // is nil it will panic
    if lang == nil {
        panic("Error: Language cannot be nil")
    }
      
    // When the value of aname
    // is nil it will panic
    if aname == nil {
        panic("Error: Author name cannot be nil")
    }
  
    // When the values of the lang and aname
    // are non-nil values it will 
    // print normal output
    fmt.Printf("Author Language: %s \n Author Name: %s\n", *lang, *aname)
}
  
// Main function
func main() {
  
    A_lang := "GO Language"
  
    // Defer statement
    defer fmt.Println("Defer statement in the Main function")
  
    // Here in entry function, we pass
    // one non-nil and one-nil value
    // Due to nil value this method panics
    entry(&A_lang, nil)
}

chevron_right


Output:

Defer statement in the entry function
Defer statement in the Main function
panic: Error: Author name cannot be nil

goroutine 1 [running]:
main.entry(0x41a780, 0x0)
    /tmp/sandbox121565297/prog.go:24 +0x220
main.main()
    /tmp/sandbox121565297/prog.go:44 +0xa0

Note: Defer statement or function always run even if the program panics.

Usage of Panic:

  • You can use panic for an unrecoverable error where the program is not able to continue its execution.
  • You can also use panic if you want an error for a specific condition in your program.


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.