scala catching exceptions

Here’s a way to deal with possible exceptions in Scala. Let’s say your application takes command line arguments, and it will work with either 2 or 3 arguments. The thing is, if you have 2 and you try to acces the 3rd, you’ll get an ArrayIndexOutOfBoundsException. Of course, you could check the size before accessing. But, let’s just see another way:

import scala.util.control.Exception._

val firstArgument     = args(0)
val secondArgument = args(1)
val thirdArgument     = catching(classOf[ArrayIndexOutOfBoundsException]).opt(args(2)).getOrElse("default value")


0 Responses to “scala catching exceptions”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog Stats

  • 238,127 hits

%d bloggers like this: