Panic {.en}

恐慌 {.zh}

::: {.en} A panic typically means something went unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn’t occur during normal operation, or that we aren’t prepared to handle gracefully. :::

::: {.zh}

“恐慌”通常意味着出乎意料的错误。大多数情况下,我们使用它来快速失败,在正常操作期间不会发生错误,或者我们不准备优雅地处理。

:::

  1. package main
  2. import "os"
  3. func main() {

::: {.en} We’ll use panic throughout this site to check for unexpected errors. This is the only program on the site designed to panic. :::

::: {.zh}

我们将在整个站点中使用恐慌来检查预期的错误。这是该网站上唯一一个旨在恐慌的程序。

:::

  1. panic("a problem")

::: {.en} A common use of panic is to abort if a function returns an error value that we don’t know how to (or want to) handle. Here’s an example of panicking if we get an unexpected error when creating a new file. :::

::: {.zh}

恐慌的一个常见用途是在函数返回我们不知道如何(或想要)处理的错误值时中止。如果我们在创建新文件时遇到意外错误,这是一个“西班牙语”的示例。

:::

  1. _, err := os.Create("/tmp/file")
  2. if err != nil {
  3. panic(err)
  4. }
  5. }

::: {.en} Running this program will cause it to panic, print an error message and goroutine traces, and exit with a non-zero status. :::

::: {.zh}

运行此程序将导致它出现紧急情况,打印错误消息和goroutine跟踪,并退出非零状态。

:::

  1. $ go run panic.go
  2. panic: a problem
  3. goroutine 1 [running]:
  4. main.main()
  5. /.../panic.go:12 +0x47
  6. ...
  7. exit status 2

::: {.en} Note that unlike some languages which use exceptions for handling of many errors, in Go it is idiomatic to use error-indicating return values wherever possible. :::

::: {.zh}

请注意,与使用异常处理许多错误的某些语言不同,在Go中,尽可能使用错误指示返回值。

:::