异常抛出的类型为“Nothing”?

An exception throw has type `Nothing`?

如此处所述 - Chapter 7 of Programming in Scala, Built-in Control Structures, 7.4 Exception handling with try expressions:

In Scala, throw is an expression that has a result type.

Technically, an exception throw has type Nothing. You can use a throw as an expression even though it will never actually evaluate to anything. This little bit of technical gymnastics might sound weird, but is frequently useful in cases like the previous example. One branch of an if computes a value, while the other throws an exception and computes Nothing. The type of the whole if expression is then the type of that branch which does compute something.

例子是:

val half =
  if (n % 2 == 0)
    n / 2
  else
    throw new RuntimeException("n must be even")

然后我去Scala试试:

scala> val n = 1
n: Int = 1

scala> val half = if (n % 2 == 0) n / 2 else throw new RuntimeException("n must be even")
java.lang.RuntimeException: n must be even
  ... 29 elided

scala> half
<console>:12: error: not found: value half
       half
       ^

表示没有找到half。但是,根据这本书,我认为它应该说它已定义并且类型为 Nothing

这是怎么回事?

It is saying that half is not found. However, based on the book, I assume it should say it is defined and it is with type Nothing.

如果你重读那段话,你会发现 half 的类型不应该是 Nothing,它应该是 Int:

The type of the whole if expression is then the type of that branch which does compute something.

计算值的分支产生类型Int。您可以通过将 half 定义为方法而不是值来证明这一点:

scala> def half = if (n % 2 == 0) n / 2 else throw new RuntimeException("n must be even")
half: Int

如果您真的想看到 throw 的类型为 Nothing,请将其添加到您的 IDE 中并使其显示类型:

val exception: Nothing = throw new RuntimeException("n must be even")

关于 half,它没有找到,因为它的声明抛出异常,这使得 REPL 无法将值绑定到它。