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".
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.
Program/Source Code:
The source code to demonstrate the panic() function is given below. The given program is compiled and executed successfully.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer