Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




GO - PANIC IN ERROR


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.


Example :



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)
}


Output :



 division by zero

In the above case, you tried to divide the number '4' by '0'. And you ended up with the below Error.


division by zero

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.


Example :



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)
}


Output :



 panic: Divide by zero not allowed and the program execution has to be stopped

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.


panic: Divide by zero not allowed and the program execution has to be stopped