top | item 38230474

(no title)

nishs | 2 years ago

There are two "kinds" of panics: those initiated by the Go runtime, and those initiated by the program author, though technically there isn't a distinction. When you access an array out of bounds, the Go runtime initiates the panic. On the other hand, for a condition that the program should hold but doesn't, the program author should initiate the panic. For example, in the exhaustive switch below, reaching the default case means that either you have somehow incorrectly allowed the construction of an invalid token value earlier in your program, or you have missed to account for a valid token value in this function.

  func (t token) symbol() byte {
          switch t {
                  case add: return '+'
                  case sub: return '-'
                  case mul: return '*'
                  case quo: return '/'
                  default:  panic("unknown token")
          }
  }
Errors are different. For example, url.Parse returns an error if its input string is an invalidly formatted URL.

  package url
  func Parse(rawURL string) (*URL, error)

discuss

order

galangalalgol|2 years ago

That is a great example of a reason to panic. There is nothing you can do at that point but return an error or panic, and something has really gone wrong if you are pulling bad tokens out of a hashmap you made yourself, tonthe point I think you should panic. Sadly, almost all the panics I see coming out of rust crates are because someone called unwrap instead of handling the error case.

zoky|2 years ago

That is a terrible example of a reason to panic. If the programmer believes the list to be exhaustive and it isn’t, then the programmer is wrong. So raise an exception and let the caller decide what to do with it. But don’t punish the caller by forcing it to crash just because you made a mistake as a programmer.

nishs|2 years ago

(in go, "raise an exception" means "return an error.")

error values are meant to represent expected, unsuccessful conditions—internal properties of the program—during the program's execution. for example, looking up the address for a domain name is an operation that can be expected to fail at times, and an error is appropriate here.

errors in go are not meant to represent properties external to the program, such as mistakes by the package author or documented incorrect usage of the package by the package user. in go these are panics.

perhaps other languages use exceptions for both but that conflates.