Exception Example

scala> :paste
// Entering paste mode (ctrl-D to finish)

// Best Practice : Exceptions are NOT recommended in Scala
// Might need to use when we are dealing with Java APIs
//#Programming Scala:83
//psn > a30 > a50
//Example : Identifying the file size
import scala.io.Source
import scala.util.control.NonFatal
object ReadFile {
  def main(args: Array[String]) = {
    args.foreach{ arg =>
                  println(s"arg -> $arg")
                  countLineSize(arg)  
                }
  }
  
  // Count no of lines in the given File
  def countLineSize(fileName: String) = {
    println("Inside countLineSize()")
    var source: Option[Source] = None
    try {
      source = Some(Source.fromFile(fileName))
      val size = source.get.getLines.size
      println(s"file $fileName has $size lines")
    }catch {
      //*** Instead of using Separate Catch Clause to handle
      //    every exception type, we can use pattern matching
      case NonFatal(x) => println(s"Non fatal exception -> $x")
    }finally {
        // Extract 'Source' from 'Option'
        for (s <- source) {
            println(s"Closing file $fileName...")
            s.close
       }
    }
  }
  
}

// Exiting paste mode, now interpreting.

import scala.io.Source
import scala.util.control.NonFatal
defined module ReadFile

scala>  ReadFile.main(Array("./testfile.txt"))
arg -> ./testfile.txt
Inside countLineSize()
Non fatal exception -> java.io.FileNotFoundException: ./testfile.txt (No such file or directory)

No comments:

Post a Comment