00.scala2014. 3. 28. 13:19
반응형

Sometimes when you're writing Scala code, you need to create a null variable (a var, not a val), such as when you need to declare a variable right before using it in a try, catch, finally block. I just ran into this when writing a Scala IMAP email client, where I needed to create two variables right before the trydeclaration, so I could reference the fields in the try block and also in the finally block.

The way you declare a null var variable in Scala is like this:

var store: Store = null
var inbox: Folder = null

As you can see from that code, the secret is knowing that you have to assign the type to the variable when you declare it. If you don't do this, Scala won't know the data type of the variable, so it won't allow you to do this, but if you do it, Scala will be happy.

A complete example

As for my specific problem -- needing to declare a Scala variable right before a try/catch/finally clause -- here's what the solution looks like:

// (1) declare the null variables
var store: Store = null
var inbox: Folder = null

try {
  // (2) use the variables/fields in the try block
  store = session.getStore("imaps")
  inbox = getFolder(store, "INBOX")
  // rest of the code here ...
  catch {
    case e: NoSuchProviderException =>  e.printStackTrace()
                                        System.exit(1)
    case me: MessagingException =>      me.printStackTrace()
                                        System.exit(2)
} finally {
  // (3) use the variables/fields in the finally clause
  inbox.close
  store.close
}

In summary, I hope this short example of how to declare an empty/null variable before a try/catch block in Scala has been helpful.

Posted by 1010
00.scala2014. 3. 28. 13:13
반응형

Scala FAQ: Can you share some examples of the Scala try/catch/finally syntax? Also, can you show how to catch multiple exceptions, and just one exception with the Scala wildcard operator (_)?

The general Scala try/catch/finally syntax looks like this:

try
{
  // your scala code here
} 
catch
{
  case foo: FooException => handleFooException(foo)
  case bar: BarException => handleBarException(bar)
  case _ => println("Got some other kind of exception")
}
finally
{
  // your scala code here, such as to close a database connection
}

As you can see, the Scala try-catch-finally syntax is similar to the Java try-catch-finally syntax, except for the catch area, which uses Scala's pattern matching capabilities to handle the different exceptions you might run into.

In that example, I'm intentionally catching a FooException and a BarException, and then I'm using the Scala "_" wildcard operator to catch any other exceptions that might occur.

Using the Scala _ wildcard operator in a catch clause

One drawback of using Scala's wildcard character (_) in a catch clause is that you can't refer to it in your code, such as if you want to print the exception.

In the excellent book, Programmming Scala, the authors suggest naming your exception variable instead of using the wildcard, which you can then refer to in your own code, something like this:

try
{
  // your scala code here
} 
catch
{
  case foo: FooException => handleFooException(foo)
  case bar: BarException => handleBarException(bar)
  
  // handling any other exception that might come up
  case unknown => println("Got this unknown exception: " + unknown)
}
finally
{
  // your scala code here, such as to close a database connection
}

As you can see from that code, I just name a variable "unknown", which I can then refer to by name.

Printing a Scala exception's stack trace

Finally, here's another Scala try/catch example, where I demonstrate how to print the stack trace from an exception:

def runAppleScriptCommand(c: AppleScriptCommand) {
  val scriptEngineManager = new ScriptEngineManager
  val appleScriptEngine = scriptEngineManager.getEngineByName("AppleScript")
  try {
    appleScriptEngine.eval(c.command)
  } catch {
    case e: ScriptException => e.printStackTrace
  }
}

Scala try/catch/finally examples - Summary

I hope these examples of the Scala try/catch/finally syntax have been helpful. As usual, if you have any questions, comments, corrections, or better examples, just leave a note in the comments section below.

Posted by 1010