Scala exception handling


Release date:2023-11-22 Update date:2023-11-22 Editor:admin View counts:173

Label:

Scala exception handling

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.

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

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.

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...

Powered by TorCMS (https://github.com/bukun/TorCMS).