JAVA DEVELOPER SITE
 

Scala - Exception Handling


Scala's exceptions very similar exceptions in many other languages like Java.

when you handle exceptions, use a try{...}catch{...} block like you would in Java except that the catch block uses matching to identify and handle the exceptions.

both are try {...}catch{...} block element are just like Java Programming.

Throwing Exceptions

Scala Throwing an exception same as in Java.
You create an exception object and then you throw it with the throw keyword as follows.
throw new IllegalArgumentException

Catching Exception

Scala provide try/catch exception in single block and then perform pattern matching against it using case blocks.

import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException

object Demo {
   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")
         }
      }
   }
}

Output

Missing file exception