Scala 在哪些情况下尝试捕获异常?

Scala 在哪些情况下尝试捕获异常?,scala,exception,try-catch,Scala,Exception,Try Catch,我刚刚开始学习Scala,所以这可能是一个简单的问题。我想使用try-catch块来检查变量是否已声明 如果变量不存在,我使用try-catch块并捕获NoSuchElementException try{ print(testVariable) } catch{ case e: NoSuchElementException => print("testVariable not found") } 我的代码显示了一个testVariable不存在的错误,而不是引发异常。然后,我还

我刚刚开始学习Scala,所以这可能是一个简单的问题。我想使用try-catch块来检查变量是否已声明

如果变量不存在,我使用try-catch块并捕获
NoSuchElementException

try{
  print(testVariable)
}
catch{
  case e: NoSuchElementException => print("testVariable not found")
}
我的代码显示了一个
testVariable
不存在的错误,而不是引发异常。然后,我还尝试了多个其他异常,但Scala的try-catch似乎没有捕捉到任何异常(除除以零的异常)

有人能告诉我如何使用Scala的try-catch块吗?

在Scala(或几乎所有编译的编程语言)中,检查变量是否已声明是编译器的工作,在编译时完成。如果您试图使用一个尚未声明的变量,编译器将给出一个错误,您的代码将无法运行

异常是在运行时表示问题的一种方法

“编译时”和“运行时”之间没有重叠,所以您试图做的事情没有意义对于“变量不存在”没有例外,这就是您无法捕获它的原因。

相比之下,以这个例子为例:

val map = Map('a' -> 1, 'b' -> 2)
map('c') // will throw NoSuchElementException because there is no 'c' in the map
在这种情况下,
map.apply('c')
(用于
apply
的语法sugar让您执行
map('c')
将引发异常,因为这就是map的apply方法的实现方式。查看键不在映射中时的调用;
map#default
会引发NoSuchElementException

您可以通过try/catch捕获该异常,例如

try {
  map('c')
} catch {
   case e: NoSuchElementException =>
     println("got it!")
}

如何抛出异常?