...

Web Technologies - Go Language

Back to Course

Lesson Description


Lession - #370 Go-Error Handling


Go - Error Handling

Go programming gives a straightforward mistake taking care of system with inbuilt blunder interface kind of the accompanying announcement −

Syntax:

type error interface {
   Error(>
string }


Functions regularly return mistake as last bring esteem back. Use errors.New to develop a fundamental blunder message as following −

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


Use return value and error message.

result, err:= Sqrt(-1>
if err != nil { fmt.Println(err>
}


Example

package main

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

func Sqrt(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:= Sqrt(-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>
} }


When the above code is compiled and executed, it produces the following result −

Math: negative number passed to Sqrt
3