- Go Tutorial
- Go - Home
- Go - Overview
- Go - Environment Setup
- Go - Program Structure
- Go - Basic Syntax
- Go - Data Types
- Go - Variables
- Go - Constants
- Go - Operators
- Go - Decision Making
- Go - Loops
- Go - Functions
- Go - Scope Rules
- Go - Strings
- Go - Arrays
- Go - Pointers
- Go - Structures
- Go - Slice
- Go - Range
- Go - Maps
- Go - Recursion
- Go - Type Casting
- Go - Interfaces
- Go - Error Handling
- Go Useful Resources
- Go - Questions and Answers
- Go - Quick Guide
- Go - Useful Resources
- Go - Discussion
Go - Error Handling
Go programming provides a pretty simple error handling framework with inbuilt error interface type of the following declaration −
type error interface { Error() string }
Functions normally return error as last return value. Use errors.New to construct a basic error 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
Advertisements