Go Wiki:PanicAndRecover

目錄

Panic

panicrecover 函式的行為類似於其他語言中的例外和 try/catch,因為 panic 會導致程式堆疊開始解開,而 recover 可以停止它。延後函式仍會在堆疊解開時執行。如果在這樣的延後函式內呼叫 recover,堆疊將停止解開,而 recover 會傳回傳遞給 panic 的值(作為 interface{})。執行階段也會在特殊情況下發生恐慌,例如對陣列或區段進行超出範圍的索引。如果 panic 導致堆疊在任何執行 goroutine 之外解開(例如 main 或傳遞給 go 的頂層函式無法從中復原),程式會退出,並附上所有執行 goroutine 的堆疊追蹤。panic 無法由不同的 goroutine recover

在套件中的用法

根據慣例,不應允許任何明確的 panic() 跨越套件邊界。應透過傳回錯誤值來向呼叫者指出錯誤狀況。不過,在套件內部,特別是在對非外傳函式進行深度巢狀呼叫時,使用 panic 來指出應轉換為呼叫函式錯誤的錯誤狀況可能會很有用(且能改善可讀性)。以下是巢狀函式和外傳函式可能透過這種 panic-on-error 關係進行互動的公認人工範例。

// A ParseError indicates an error in converting a word into an integer.
type ParseError struct {
    Index int    // The index into the space-separated list of words.
    Word  string // The word that generated the parse error.
    Error error  // The raw error that precipitated this error, if any.
}

// String returns a human-readable error message.
func (e *ParseError) String() string {
    return fmt.Sprintf("pkg: error parsing %q as int", e.Word)
}

// Parse parses the space-separated words in input as integers.
func Parse(input string) (numbers []int, err error) {
    defer func() {
        if r := recover(); r != nil {
            var ok bool
            err, ok = r.(error)
            if !ok {
                err = fmt.Errorf("pkg: %v", r)
            }
        }
    }()

    fields := strings.Fields(input)
    numbers = fields2numbers(fields)
    return
}

func fields2numbers(fields []string) (numbers []int) {
    if len(fields) == 0 {
        panic("no words to parse")
    }
    for idx, field := range fields {
        num, err := strconv.Atoi(field)
        if err != nil {
            panic(&ParseError{idx, field, err})
        }
        numbers = append(numbers, num)
    }
    return
}

為了展示此行為,請考慮以下 main 函式

func main() {
    var examples = []string{
        "1 2 3 4 5",
        "100 50 25 12.5 6.25",
        "2 + 2 = 4",
        "1st class",
        "",
    }

    for _, ex := range examples {
        fmt.Printf("Parsing %q:\n  ", ex)
        nums, err := Parse(ex)
        if err != nil {
            fmt.Println(err)
            continue
        }
        fmt.Println(nums)
    }
}

參考資料

延後、恐慌和復原

https://go.dev.org.tw/ref/spec#Handling_panics

https://go.dev.org.tw/ref/spec#Run_time_panics


此內容是 Go Wiki 的一部分。