{"record":{"id":"dbf224aa33d605b0","repo":"unknwon/the-way-to-go_ZH_CN","slug":"a-severe-error-occurred-stopping-the-program","errorCode":null,"errorMessage":"A severe error occurred: stopping the program!","messagePattern":"A severe error occurred: stopping the program!","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"eBook/13.2.md","lineNumber":14,"sourceCode":"# 13.2 运行时异常和 panic\n\n当发生像数组下标越界或类型断言失败这样的运行错误时，Go 运行时会触发*运行时 panic*，伴随着程序的崩溃抛出一个 `runtime.Error` 接口类型的值。这个错误值有个 `RuntimeError()` 方法用于区别普通错误。\n\n`panic()` 可以直接从代码初始化：当错误条件（我们所测试的代码）很严苛且不可恢复，程序不能继续运行时，可以使用 `panic()` 函数产生一个中止程序的运行时错误。`panic()` 接收一个做任意类型的参数，通常是字符串，在程序死亡时被打印出来。Go 运行时负责中止程序并给出调试信息。在示例 13.2 [panic.go](examples/chapter_13/panic.go) 中阐明了它的工作方式：\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"Starting the program\")\n\tpanic(\"A severe error occurred: stopping the program!\")\n\tfmt.Println(\"Ending the program\")\n}\n```\n\n输出如下：\n\n```\nStarting the program\npanic: A severe error occurred: stopping the program!\npanic PC=0x4f3038\nruntime.panic+0x99 /go/src/pkg/runtime/proc.c:1032\n       runtime.panic(0x442938, 0x4f08e8)\nmain.main+0xa5 E:/Go/GoBoek/code examples/chapter 13/panic.go:8\n       main.main()\nruntime.mainstart+0xf 386/asm.s:84\n       runtime.mainstart()\nruntime.goexit /go/src/pkg/runtime/proc.c:148\n       runtime.goexit()","sourceCodeStart":1,"sourceCodeEnd":32,"githubUrl":"https://github.com/unknwon/the-way-to-go_ZH_CN/blob/7a54d34d3657084b6a59e5618bd069b912d571aa/eBook/13.2.md#L1-L32","documentation":"Deliberate teaching panic in example 13.2 (panic.go): main prints one line, then calls panic(\"A severe error occurred: stopping the program!\"). It demonstrates panic semantics — the runtime prints the panic value with a stack trace, deferred functions run during unwinding, the program crashes, and the fmt.Println after the panic is unreachable.","triggerScenarios":"Unconditional: every execution of the demo binary reaches the panic call after the first Println. No environment, input, or configuration triggers it — it is the lesson itself.","commonSituations":"New Go developers running the eBook example to observe panic output; copy-pasting the demo skeleton into real code and forgetting to remove the panic; expecting 'Ending the program' to print (it never will).","solutions":["If hit while studying the book: this is the expected output — nothing is broken","In real code, remove the panic and use normal control flow (return an error, os.Exit with a status)","If aborting is genuinely intended, prefer log.Fatal for a clean single-line exit","Run with 'go run panic.go' and read the unwind trace to learn the defer/panic interaction"],"exampleFix":"// before\nfmt.Println(\"Starting the program\")\npanic(\"A severe error occurred: stopping the program!\")\nfmt.Println(\"Ending the program\")\n\n// after\nfmt.Println(\"Starting the program\")\nif err := doWork(); err != nil {\n    log.Fatalf(\"A severe error occurred: %v\", err)\n}\nfmt.Println(\"Ending the program\")","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"// capture the demo panic instead of crashing\ndefer func() {\n    if r := recover(); r != nil {\n        fmt.Println(\"recovered from demo panic:\", r)\n    }\n}()\nfmt.Println(\"Starting the program\")\npanic(\"A severe error occurred: stopping the program!\")","preventionTips":["Strip demo panics before shipping copied skeleton code","Reserve panic for unrecoverable invariant violations, not control flow","Use error values or log.Fatal for expected failure paths"],"tags":["go","panic","tutorial","runtime","crash"],"backgroundTag":null,"analyzedSha":"7a54d34d3657084b6a59e5618bd069b912d571aa","analyzedAt":"2026-08-15T15:13:06.026Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}