ADVERTISEMENT
ADVERTISEMENT

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

Problem Solution:

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".

Program/Source Code:

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.


ADVERTISEMENT


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.