Latest web development tutorials

Scala Exception Handling

Scala exception handling and other similar languages ​​such as Java.

Scala's method may throw an exception by way of a method to terminate the relevant code, without going through the return value.


Throw an exception

Scala and Java methods throw exceptions, the use of throw methods, for example, throw a new exception parameters:

throw new IllegalArgumentException

Catch the exception

Abnormal capture mechanism with other languages, if an exception occurs, catch words are sequentially captured. Thus, in the words of the catch, the more specific exception to rely more before and after the more common abnormalities more reliable. If an exception does not catch the words, the exception will not be processed and will be upgraded to the callee.

Catch exception catch clause, grammar and other languages ​​are not the same. In Scala, the borrowed ideas do pattern matching to match an exception, so the catch code, the case is a series of words, as in this 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")
         }
      }
   }
}

Implementation of the above code, the output is:

$ scalac Test.scala 
$ scala Test
Missing file exception

catch phrase in the content with the match in the case is exactly the same. Because exception handling is in sequence, if the most common abnormality, Throwable, written in the front, in the back of the case that are not catch, so you need to write it last.


finally statement

finally statement is used to execute either normal processing or the steps need to be performed when an exception occurs, the examples are 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...")
      }
   }
}

Implementation of the above code, the output is:

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