Sunday, September 18, 2016

try/catch Expression : Example

#165
scala> def getMark(subject: String):Int = {
     |    try {
     |       if(subject == "math") {
     |          80
     |       }else {
     |          throw new RuntimeException
     |       }
     |    }catch{
     |       //Pattern Matching is used in 'catch' clause
     |       case ex : RuntimeException => {
     |          println("Runtime Exception...")
     |          75
     |       }
     |       case _: Throwable => 50
     |    }finally{
     |       println("This statement always get executed...")
     |    }
     | }
getMark: (subject: String)Int

scala>

scala>

scala> getMark("math")
This statement always get executed...
res70: Int = 80

scala> getMark("science")
Runtime Exception...
This statement always get executed...
res71: Int = 75