golang tutorial - Error Handling In Golang | Error Handling In Go - golang - go programming language - google go - go language - go program - google language



Error Handling In Golang

  • Exception handling is the process of responding to the occurrence, during computation.
  • It often change the normal flow of program execution.
  • In general, an exception breaks the normal flow of execution and executes a pre-registered exception handler methods created by the developers.
  • Other options for exception handling in software is error checking, which maintains normal program flow.
 if statement
type error interface {
   Error() string
}
click below button to copy the code. By - golang tutorial - team
  • Functions normally return error as last return value. Use errors.New to construct a basic error message as following:
func MathFunction(value float64)(float64, error) {
   if(value < 0){
      return 0, errors.New("Math: negative number passed to Sqrt")
   }
   return math.Sqrt(value)
}
click below button to copy the code. By - golang tutorial - team

Use return value and error message.

result, err:= Sqrt(-1)

if err != nil {
   fmt.Println(err)
}
click below button to copy the code. By - golang tutorial - team

Example

package main

import "errors"
import "fmt"
import "math"

func MathFunction (value float64)(float64, error) {
   if(value < 0){
      return 0, errors.New("Math: negative number passed to Sqrt")
   }
   return math.Sqrt(value), nil
}

func main() {
   result, err:= MathFunction (-1)

   if err != nil {
      fmt.Println(err)
   }else {
      fmt.Println(result)
   }
   
   result, err = Sqrt(9)

   if err != nil {
      fmt.Println(err)
   }else {
      fmt.Println(result)
   }
}
click below button to copy the code. By - golang tutorial - team
 if statement
golang , gopro , google go , golang tutorial , google language , go language , go programming language

output for the above go language program

Math: negative number passed to Sqrt
3

Related Searches to Error Handling In Golang | Error Handling In Go