Go by Example: Panic

The panic function in Go is used to raise a runtime error, causing a program to exit immediately and print a stack trace. panic is typically used when a program encounters an unexpected error or situation that it cannot recover from. Here’s an example of using panic:

package main

import (
	"fmt"
)

func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Recovered from panic:", r)
		}
	}()

	numbers := []int{7, 4, 8, 0, 9, 1}
	for i, num := range numbers {
		if num == 0 {
			panic("division by zero")
		}
		fmt.Println(100 / num, "at index", i)
	}
}

In this example, a defer statement is used to register a function that will be called when the function it is called in (in this case, main) returns. The registered function uses the recover function to recover from a panic, printing a message indicating that the panic was recovered from and the value passed to panic. The for loop then iterates over a slice of integers, dividing 100 by each integer. If the integer is 0, the panic function is called, causing the program to exit immediately and print a stack trace. The registered defer function is then called, allowing the program to continue execution and print a message indicating that the panic was recovered from.

Here’s another example of using panic and recover to handle errors:

package main

import (
	"fmt"
	"os"
)

func readFile(filename string) {
	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	// Read the file contents
	// ...
}

func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Error:", r)
		}
	}()

	readFile("non-existent-file.txt")
}

In this example, the readFile function is used to open a file with a specified filename. If the file cannot be opened, the panic function is called with the error returned from os.Open. The main function uses a defer statement to register a function that will be called when the function it is called in returns. The registered function uses the recover function to recover from a panic, printing a message indicating the error that caused the panic. If the file specified in the call to readFile does not exist, a panic will occur, and the registered defer function will be called, allowing the program to continue execution and print a message indicating the error.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *