Easy Tutorial
❮ Scala Install Functions Variable Arguments ❯

Scala Exception Handling

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

In Scala, methods can terminate the execution of related code by throwing exceptions, without having to use return values.


Throwing Exceptions

The method of throwing exceptions in Scala is the same as in Java, using the throw method. For example, to throw a new argument exception:

throw new IllegalArgumentException

Catching Exceptions

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

The syntax for catching exceptions with catch clauses is a bit different from other languages. In Scala, the idea of pattern matching is used for exception matching. Therefore, in the catch code, there is a series of case clauses, 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")
      }
    }
  }
}

Running the above code will produce the following output:

$ scalac Test.scala 
$ scala Test
Missing file exception

The content inside the catch clause is exactly the same as in the case inside match. Since exception catching is in sequence, if the most general exception, Throwable, is written in the front, then the cases behind it will not catch, so it needs to be written at the end.


finally Statement

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

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...")
    }
  }
}

Running the above code will produce the following output:

$ scalac Test.scala 
$ scala Test
Missing file exception
Exiting finally...
❮ Scala Install Functions Variable Arguments ❯