×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to demonstrate the panic() function

Here, we are going to demonstrate the panic() function in Golang (Go Language).
Submitted by Nidhi, on April 02, 2021 [Last updated : March 05, 2023]

panic() function in Golang

In this program, we will demonstrate the use of the panic() function. The use of the panic() function is to abort if a function returns an error value that we don't know how to handle? Here, we will call the abort function with the specified message in case of "divide by zero".

Golang code to demonstrate the example of panic() function

The source code to demonstrate the panic() function is given below. The given program is compiled and executed successfully.

// Golang program to demonstrate the panic() function

package main

import "fmt"

func main() {
	var num1 int = 0
	var num2 int = 0
	var num3 int = 0

	fmt.Print("Enter num1: ")
	fmt.Scanf("%d", &num1)

	fmt.Print("Enter num2: ")
	fmt.Scanf("%d", &num2)

	if num2 == 0 {
		panic("Divide by zero")
	} else {
		num3 = num1 / num2
		fmt.Println("Result: ", num3)
	}
}

Output

RUN 1:
Enter num1: 10
Enter num2: 3
Result:  3

RUN 2:
Enter num1: 10
Enter num2: 0
panic: Divide by zero

goroutine 1 [running]:
main.main()
        /home/main.go:19 +0x2f7

Explanation

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package to formatting related functions.

In the main() function, we created three integer variables and read the value of num1, num2 from the user. Then we checked the value of variable num2. If it is 0 then we called the panic() function to abort the program and print the appropriate message on the console screen.





Comments and Discussions!

Load comments ↻





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