In the previous tutorial, we have seen that if there is a divide by zero error, we can proceed with the program execution.
But let's say we want to stop the execution if there is any error.
package main import "fmt" func main() { z := 4 / 0 fmt.Println("The divided result is ",z) k := 5 + 2 fmt.Print("The added result is ",k) }
In the above case, you tried to divide the number '4' by '0'. And you ended up with the below Error.
In other words the application panicked and it stopped.
That's what a 'panic' in Go is. If there is any error with which we cannot proceed, the application execution should be stopped.
Go provides a 'panic()' Function that will help us to specify custom error.
package main import "fmt" func division(firstNum int, secondNum int) (int) { if (secondNum == 0) { panic("Divide by zero not allowed and the program execution has to be stopped") } else { result := firstNum / secondNum return result } } func main() { x := 4 y := 0 z := division(x, y) fmt.Println("The divided result is ",z) k := x + y fmt.Println("The added result is ",k) }
And as we can see that we got the custom error and the program execution is stopped.
And all we have done is, placed the 'panic()' Function in the 'if' condition where we have checked if there can be a 'divide by zero' error.
if (secondNum == 0) { panic("Divide by zero not allowed and the program execution has to be stopped") }
And the program execution has stopped printing the panic message as output.