Golang: Error Handling in Go Programming


Return Error


package main

import (
	"errors"
	"fmt"
)

func sum(a int, b int) (int, error) {

	x := a + b

	if a < 0 || b < 0 {
		return x, errors.New("value should be greater than zero")
	}

	return x, nil
}

func main() {
	a := 12
	b := -1

	x, err := sum(a, b)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(x)
}

Panic and Recover from panic

package main

import (
	//	"errors"
	"fmt"
)

func sum(a int, b int) (int, error) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("Wow Error: ", err)
		}
	}()

	x := a + b

	if a < 0 || b < 0 {
		panic("I am panicking kaka")
	}

	return x, nil
}

func main() {
	a := 12
	b := -1

	x, err := sum(a, b)

	fmt.Println(x)
	fmt.Println(err)
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s