Reputation: 659
I am new to scala and have a requirement where i have to continue processing the next records when an exception arises.
object test {
def main(args: Array[String]) {
try {
val txt = Array("ABC", "DEF", "GHI")
val arr_val = txt(3)
println(arr_val)
val arr_val1 = txt(0)
println(arr_val1)
scala.util.control.Exception.ignoring(classOf[ArrayIndexOutOfBoundsException]) {
println { "Index ouf of Bounds" }
}
} catch {
case ex: NullPointerException =>
}
}
}
I tried ignoring the exception , but the value of arr_val1
is not getting printed because of the ArrayIndexOutOfBoundsException which arises ahead of this line.
Any help would be highly appreciated
Upvotes: 0
Views: 2920
Reputation: 20295
scala.util.Try
can be used to capture the value of a computation that may contain a value or throw an exception. So, in your example txt(0)
should contain the value "ABC" and txt(3)
will thrown an exception. In each case you want to print out something different.
Here's a similar example to iterate through some made up indices in a List
and try to access that index in txt
. Some of these will result in a value and some will fail. In both cases that result is captured in the Try
as a Success
or Failure
. Based on which type is returned a message is printed similar to your example.
scala> List(0,1,3,2,4,5).foreach(x => println(Try(txt(x)).getOrElse(println("Index ouf of bounds"))))
ABC
DEF
Index ouf of bounds
()
GHI
Index ouf of bounds
()
Index ouf of bounds
()
Upvotes: 2