English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Scala Exception Handling

Scala's exception handling is similar to other languages like Java.

Scala's methods can terminate the execution of related code by throwing exceptions, without needing to return a value.

Throw exception

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

throw new IllegalArgumentException

Catch exception

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

The catch clause for exception handling is different from other languages. In Scala, the idea of pattern matching is borrowed to match exceptions, so in the code of the catch, it is a series of case clauses, 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")
      }
         case ex: FileNotFoundException => {
            println("Missing file exception")
         }
         case ex: IOException => {
            println("IO Exception")
         }
      }
   }
}

Execute the following code, and the output will be:

$ scalac Test.scala 
$ scala Test
Missing file exception

The content in the catch clause is exactly the same as the case in the match. Since exception handling is in order, if the most general exception, Throwable, is written at the beginning, then the cases after it will not be caught. Therefore, it needs to be written at the end.

finally statement

The finally statement is used to execute steps that need to be executed whether the normal processing is performed or an exception occurs, 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")
      }
         case ex: FileNotFoundException => {
            println("Missing file exception")
         }
         case ex: IOException => {
            println("IO Exception")
         }
      } finally {
         println("Exiting finally...")
      }
   }
}

Execute the following code, and the output will be:

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