8.40. Scala exception handling

发布时间 : 2025-10-25 13:35:16 UTC      

Page Views: 9 views

Scala’s exception handling is similar to other languages such as Java.

Scala’s method can terminate the execution of the relevant code by throwing an exception, without having to return a value.

8.40.1. Throw an exception #

Scala throws an exception in the same way as Java, using the throw Method, for example, throw a new parameter exception:

throw new IllegalArgumentException 

8.40.2. Catch exception #

The mechanism of exception catching is the same as in other languages, if anexception occurs catch words are captured in order. Therefore, in catch in the sentence, the more specific exception is, the more common the exception is, the more backward the exception is. If the exception thrown is not in the catch . The exception cannot be handled and is escalated to the caller.

Catch abnormal catch clause, the grammar is quite different from that in other languages. In Scala, the idea of pattern matching is borrowed to doabnormal matching, so catch in the code, is a series of case sentence, as shown in the following example:

Example #

import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object Test { def main(args: Array[String]) { try { val f = new FileReader("input.txt") } catch { case ex: FileNotFoundException =>{ println("Missing file exception") } case ex: IOException => { println("IO Exception") } } } } 

Execute the above code, and the output is as follows:

$ scalac Test.scala $ scala Test Missing file exception 

The catch content in the sentence is similar to that in the sentence match in case is exactly the same. Because the exception catch isin order, if the most common exception Throwable written at the front and behind it case none of them can be captured, so you need to write it at the end.

8.40.3. Finally statement #

finally statement is used to perform steps that need to be performed regardless of normal processing or when an exception occurs, as an example:

Example #

import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object Test { def main(args: Array[String]) { try { val f = new FileReader("input.txt") } catch { case ex: FileNotFoundException => { println("Missing file exception") } case ex: IOException => { println("IO Exception") } } finally { println("Exiting finally...") } } } 

Execute the above code, and the output is as follows:

$ scalac Test.scala $ scala Test Missing file exception Exiting finally... 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。