简体   繁体   English

异常抛出类型为“Nothing”?

[英]An exception throw has type `Nothing`?

As stated here - Chapter 7 of Programming in Scala, Built-in Control Structures, 7.4 Exception handling with try expressions : 如此处所述 - Scala编程的第7章,内置控制结构,7.4使用try表达式进行异常处理

In Scala, throw is an expression that has a result type. 在Scala中,throw是一个具有结果类型的表达式。

Technically, an exception throw has type Nothing . 从技术上讲,异常抛出类型为Nothing You can use a throw as an expression even though it will never actually evaluate to anything. 你可以使用throw作为表达式,即使它实际上永远不会评估任何东西。 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 . if的一个分支计算一个值,而另一个分支抛出异常并计算Nothing The type of the whole if expression is then the type of that branch which does compute something. 整个if表达式的类型是那个计算某事物的分支的类型。

The example is: 例子是:

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

Then I went to Scala and try: 然后我去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
       ^

It is saying that half is not found. 据说没有找到half However, based on the book, I assume it should say it is defined and it is with type Nothing . 但是,基于这本书,我认为它应该说它是定义的,它的类型为Nothing

What's wrong here? 这有什么不对?

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. 但是,基于这本书,我认为它应该说它是定义的,它的类型为Nothing。

If you re-read that paragraph, you'll see that the type of half shouldn't be Nothing , it should be Int : 如果你重新阅读那段,你会看到half的类型不应该是Nothing ,它应该是Int

The type of the whole if expression is then the type of that branch which does compute something. 整个if表达式的类型是那个计算某事物的分支的类型。

The branch which does compute a value produces the type Int . 计算值的分支产生Int类型。 You can prove this by defining half as a method and not a value: 您可以通过将half定义为方法而不是值来证明这一点:

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

If you actually want to see that throw has type Nothing , add it in your IDE and make it show the type: 如果您确实希望看到throw类型为Nothing ,请将其添加到IDE中并使其显示类型:

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

Regarding half , it isn't found because it's declaration throws an exception, which makes the REPL unable to bind a value to it. 关于half ,找不到它,因为它的声明抛出一个异常,这使得REPL无法绑定一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM