Scala exception handling


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

Scala's methods can terminate the execution of related code by throwing exceptions without returning a value.


Throwing exceptions

Scala throws exceptions in the same way as Java, using the throw method, for example, throwing a new parameter exception:

throw new IllegalArgumentException

Catch exceptions

The exception catching mechanism is the same as in other languages. If an exception occurs, the catch clauses are captured in order. Therefore, in the catch clause, the more specific exceptions should be placed first, and the more general exceptions should be placed later. If the exception thrown is not in the catch clause, the exception cannot be handled and will be escalated to the caller.

The syntax of the catch clause for catching exceptions is different from that in other languages. In Scala, the idea of ​​pattern matching is borrowed to do exception matching. Therefore, in the catch code, there is a series of case statements, as shown in the following 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 result is:

$ scalac Test.scala 
$ scala Test
Missing file exception

The content in the catch clause is exactly the same as the case in match. Since exceptions are caught in order, if the most common exception, Throwable, is written at the front, the cases following it will not be caught, so it needs to be written at the end.


finally statement

The finally statement is used to execute the steps that need to be executed whether it is normal processing or when an exception occurs. The example is as follows:

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 , the output result is:

$ scalac Test.scala 
$ scala Test
Missing file exception
Exiting finally...