0

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

1 Answer 1

2

scala.util.Trycan 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
()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.