Scala try catch and finally

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-08 13:47:28 Viewed : 198


Scala try catch and finally 

Similar to Java, but its syntax is consistent with match expressions: 

try {

    writeToFile(text)

} catch {

    case fnfe: FileNotFoundException => println(fnfe)

    case ioe: IOException => println(ioe)

} 

Example:

Following example illustrates about Scala try catch and finally

Save the file as −  TryCatchFinallyEx.scala 

TryCatchFinallyEx.scala 

package runnerdev

class ExceptionExample {

  def divide(x: Int, y: Int) = {

    try {

      x / y 

    } catch {

      case e: ArithmeticException => println(e.printStackTrace())

      case ex: Exception          => println(ex)

      case th: Throwable => println("found a unknown exception" + th)

    } finally {

      println("Finaly block always executes")

    }

    println("Rest of the code is executing ")

  }

} 

object TryCatchFinallyEx {

  def main(args: Array[String]) {

    var e = new ExceptionExample()

    e.divide(10, 0) 

  }

compile and run the above example as follows 

scala> scalac TryCatchFinallyEx.scala

scala> scala TryCatchFinallyEx

 Output:

        java.lang.ArithmeticException: / by zero

                at runnerdev.ExceptionExample.divide(TryCatchFinallyEx.scala:6)

                at runnerdev.TryCatchFinallyEx$.main(TryCatchFinallyEx.scala:22)

                at runnerdev.TryCatchFinallyEx.main(TryCatchFinallyEx.scala)

                ()

        Finaly block always executes

        Rest of the code is executing

Search
Sub-Categories
Related Articles

Leave a Comment: