[Go] Error

package main

import (
	"errors"
	"fmt"
	"strings"
)

func shouldGreaterThanTen(num int) error {
	if num < 10 {
		return errors.New("Number is less than 10")
	}

	return nil // should return nil if no error
}

func openFile() error {
    f, err = os.Open("missingFile.txt")
    if err != nil {
     return err
    }
    
    defer f.Close()
    return nil
}

func main() {

	num := 9
	if err := shouldGreaterThanTen(num); err != nil {
		fmt.Println(fmt.Errorf("%d is Not greater than TEN", num))
		// panic(err) // this will throw error, stop the program
	}
    
    if err := openFile(); err != nil {
        fmt.Println(fmt.Errorf("%v", err))
    }
}

 

posted @ 2022-09-06 02:15  Zhentiw  阅读(16)  评论(0编辑  收藏  举报