Golang panic() Function with Examples

Golang | panic() Function: Here, we are going to learn about the built-in panic() function with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 20, 2021 [Last updated : March 15, 2023]

panic() Function

In the Go programming language, the panic() is a built-in function that is used to stop the normal execution of the current goroutine. When a function calls panic, the normal execution of the function stops immediately.

It accepts one parameter (v interface{}) and returns nothing.

Syntax

func panic(v interface{})

Parameter(s)

  • v : An interface type or message to print when panic has occurred.

Return Value

The return type of the panic() function is none.

Example 1

// Golang program to demonstrate the
// example of panic() function

package main

import (
	"fmt"
)

// Creating the function to return the
// result of divide (/) operation,
// and returns an error using the
// panic() function, if the dividend is 0
func Divide(a, b int) float32 {
	if b != 0 {
		return float32(a) / float32(b)
	} else {
		panic("Error: dividend cannot be 0.")
	}
}

// Main Function
func main() {
	x := 10
	y := 3

	res := Divide(x, y)
	fmt.Println("Result:", res)

	x = 10
	y = 0

	res = Divide(x, y)
	fmt.Println("Result:", res)
}

Output

Result: 3.3333333
panic: Error: dividend cannot be 0.

goroutine 1 [running]:
main.Divide(...)
	/tmp/sandbox464958966/prog.go:18
main.main()
	/tmp/sandbox464958966/prog.go:33 +0x8f

Example 2

// Golang program to demonstrate the
// example of panic() function

package main

import (
	"fmt"
)

// Defining a struct type
type student struct {
	Name   string
	Course string
	Age    int
}

// Function to print the values
// and returns an error using the
// panic() function if course's value
// is nil
func PrintStudent(x student) {
	if x.Course == "" {
		panic("Course cannot be empty.")
	} else {
		fmt.Printf("%s, %s, %d\n", x.Name, x.Course, x.Age)
	}
}

// Main Function
func main() {
	// Creating structure
	s1 := student{"Radib Kar", "B.Tech", 21}
	s2 := student{"Shivang Yadav", "BCA", 22}
	s3 := student{"Pooja Kumari", "", 28}

	// Printing the values
	PrintStudent(s1)
	PrintStudent(s2)
	PrintStudent(s3)
}

Output

Radib Kar, B.Tech, 21
Shivang Yadav, BCA, 22
panic: Course cannot be empty.

goroutine 1 [running]:
main.PrintStudent({{0x4968af, 0xc}, {0x0, 0x0}, 0x1c})
	/tmp/sandbox74714865/prog.go:23 +0x130
main.main()
	/tmp/sandbox74714865/prog.go:39 +0x173

Golang builtin Package »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.