{"record":{"id":"e78321ab9a09de92","repo":"unknwon/the-way-to-go_ZH_CN","slug":"no-words-to-parse","errorCode":null,"errorMessage":"no words to parse","messagePattern":"no words to parse","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"eBook/13.4.md","lineNumber":58,"sourceCode":"func Parse(input string) (numbers []int, err error) {\n    defer func() {\n        if r := recover(); r != nil {\n            var ok bool\n            err, ok = r.(error)\n            if !ok {\n                err = fmt.Errorf(\"pkg: %v\", r)\n            }\n        }\n    }()\n\n    fields := strings.Fields(input)\n    numbers = fields2numbers(fields)\n    return\n}\n\nfunc fields2numbers(fields []string) (numbers []int) {\n    if len(fields) == 0 {\n        panic(\"no words to parse\")\n    }\n    for idx, field := range fields {\n        num, err := strconv.Atoi(field)\n        if err != nil {\n            panic(&ParseError{idx, field, err})\n        }\n        numbers = append(numbers, num)\n    }\n    return\n}\n```\n\n示例 13.5 [panic_package.go](examples/chapter_13/panic_package.go)：\n\n```go\n// panic_package.go\npackage main\n","sourceCodeStart":40,"sourceCodeEnd":76,"githubUrl":"https://github.com/unknwon/the-way-to-go_ZH_CN/blob/7a54d34d3657084b6a59e5618bd069b912d571aa/eBook/13.4.md#L40-L76","documentation":"Guard panics inside fields2numbers (section 13.4): panic(\"no words to parse\") when strings.Fields(input) yields an empty slice, and panic(&ParseError{idx, field, err}) when strconv.Atoi rejects a token. The surrounding function demonstrates the recover pattern: a deferred closure converts the panic value back into a returned error via err = fmt.Errorf(\"pkg: %v\", r).","triggerScenarios":"An input string that is empty or whitespace-only makes strings.Fields return a zero-length slice, triggering 'no words to parse'; any token such as 'foo' or '1x' fails strconv.Atoi and panics with a *ParseError carrying index, field, and underlying error.","commonSituations":"Reading blank lines from stdin in a loop; space-separated data files with missing or malformed columns; trailing whitespace-only input passed straight from user prompts.","solutions":["Skip empty/blank input before parsing: trim the string and return early when strings.Fields(input) is empty","Validate tokens with a loop over strconv.Atoi returning an error instead of panicking on the first bad field","Keep the deferred recover wrapper so any residual panic becomes a normal error for callers","In the recover branch, type-assert *ParseError to report index/field precisely instead of a generic message"],"exampleFix":"// before\nfunc fields2numbers(fields []string) (numbers []int) {\n    if len(fields) == 0 {\n        panic(\"no words to parse\")\n    }\n    ...\n}\n\n// after\nif len(strings.Fields(input)) == 0 {\n    return nil, errors.New(\"no words to parse\")\n}","handlingStrategy":"validation","validationCode":"// pre-check the input before calling the parser\nfunc parseable(input string) bool {\n    fields := strings.Fields(input)\n    if len(fields) == 0 {\n        return false // would panic \"no words to parse\"\n    }\n    for _, f := range fields {\n        if _, err := strconv.Atoi(f); err != nil {\n            return false // would panic &ParseError\n        }\n    }\n    return true\n}","typeGuard":"// narrows a recovered panic value to *ParseError\nfunc asParseError(r interface{}) (*ParseError, bool) {\n    pe, ok := r.(*ParseError)\n    return pe, ok\n}","tryCatchPattern":"// recover-to-error wrapper, as the section itself shows\ndefer func() {\n    if r := recover(); r != nil {\n        if pe, ok := r.(*ParseError); ok {\n            err = fmt.Errorf(\"pkg: field %d (%q): %v\", pe.Index, pe.Field, pe.Err)\n        } else {\n            err = fmt.Errorf(\"pkg: %v\", r)\n        }\n    }\n}()\nnumbers = fields2numbers(strings.Fields(input))","preventionTips":["Trim and empty-check input before handing it to a Fields/Atoi pipeline","Prefer returning errors from parse helpers; keep panic/recover at one boundary","Type-assert recovered values to the structured error type for precise messages"],"tags":["go","parsing","strconv","panic","recover","strings"],"backgroundTag":null,"analyzedSha":"7a54d34d3657084b6a59e5618bd069b912d571aa","analyzedAt":"2026-08-15T15:13:06.026Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}