抛出异常的类型为“ Nothing”吗? [英] An exception throw has type `Nothing`?

查看:135
本文介绍了抛出异常的类型为“ Nothing”吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如此处所述- Scala中内置控件的第7章结构,7.4使用try表达式的异常处理


在Scala中,throw是具有结果类型的表达式。

从技术上讲,异常抛出的类型为 Nothing 。您可以将throw用作表达式,即使它实际上不会求值。这一点技术体操听起来很奇怪,但是在像前面的例子这样的情况下经常有用。 if的一个分支计算值,而另一个则引发异常并计算 Nothing 。整个if表达式的类型就是该分支的类型,它将计算某些内容。

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并尝试:

Then I went to Scala and try:

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
       ^

是说找不到一半。但是,根据这本书,我认为应该说它已定义并且类型为 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.

这里出什么问题了?

推荐答案


这就是说找不到一半。但是,根据这本书,我
假定应该说它已定义并且类型为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

If you re-read that paragraph, you'll see that the type of half shouldn't be Nothing, it should be Int:


如果表达式为

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

The branch which does compute a value produces the type Int. You can prove this by defining half as a method and not a value:

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

如果您确实想看到键入 Nothing ,将其添加到您的IDE中,并使其显示以下类型:

If you actually want to see that throw has type Nothing, add it in your IDE and make it show the type:

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

关于一半,它不是找不到,因为它的声明引发了异常,这使REPL无法将值绑定到它。

Regarding half, it isn't found because it's declaration throws an exception, which makes the REPL unable to bind a value to it.

这篇关于抛出异常的类型为“ Nothing”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆