Scala Try Catch Assignment Help

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.17, “How to declare a variable (var) before using it in try/catch/finally.”


You want to use an object in a Scala block, and need to access it in the portion of the block, such as when you need to call a method on an object.


In general, declare your field as an before the try/catch block, then create a inside the clause. This is shown in the following example, where the fields in and out are declared before the try/catch block, and assigned inside the clause:

import object CopyBytes extends App { var in = None: Option[FileInputStream] var out = None: Option[FileOutputStream] try { in = Some(new FileInputStream("/tmp/Test.class")) out = Some(new FileOutputStream("/tmp/Test.class.copy")) var c = 0 while ({c =; c != −1}) { out.get.write(c) } } catch { case e: IOException => e.printStackTrace } finally { println("entered finally ...") if (in.isDefined) in.get.close if (out.isDefined) out.get.close } }

In this code, and are assigned to before the clause, and then reassigned to values inside the clause if everything succeeds. Therefore, it’s safe to call and in the loop, because if an exception had occurred, flow control would have switched to the clause, and then the clause before leaving the method.

Normally I tell people that I wish the and methods on would be deprecated, but this is one of the few times where I think their use is acceptable, and they lead to more readable code.

Another approach you can employ inside the clause is to use the approach with a :

try { in = Some(new FileInputStream("/tmp/Test.class")) out = Some(new FileOutputStream("/tmp/Test.class.copy")) in.foreach { inputStream => out.foreach { outputStream => var c = 0 while ({c =; c != −1}) { outputStream.write(c) } } } } // ...

This is still readable with two variables, and eliminates the method calls, but wouldn’t be practical with more variables.


One key to this recipe is knowing the syntax for declaring fields that aren’t initially populated:

var in = None: Option[FileInputStream] var out = None: Option[FileOutputStream]

I had a hard time remembering this until I came up with a little mnemonic, “Var x has No Option yeT,” where I capitalize the “T” there to stand for “type.” In my brain it looks like this:

var x has No Option[yeT]

From there it’s a simple matter to get to this:

var x = None: Option[Type]

When I first started working with Scala, the only way I could think to write this code was using values. The following code demonstrates the approach I used in an application that checks my email accounts. The and fields in this code are declared as fields that have the and types (from the javax.mail package):

// (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 case me: MessagingException => me.printStackTrace } finally { // (3) call close() on the objects in the finally clause if (inbox != null) inbox.close if (store != null) store.close }

However, working in Scala gives you a chance to forget that values even exist, so this is not a recommended approach. See Recipe 20.5, “Eliminate null Values from Your Code”, for examples of how to rid your code of values.

See Also

  • The code shown in this recipe is a Scala version of this Oracle “Byte Streams” example

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

sealed abstract classTry[+T] extends AnyRef

Instance Constructors

  1. newTry()

Abstract Value Members

  1. abstract deffailed: Try[Throwable]

  2. abstract deffilter(p: (T) ⇒ Boolean): Try[T]

  3. abstract defflatMap[U](f: (T) ⇒ Try[U]): Try[U]

  4. abstract defflatten[U](implicit ev: <:<[T, Try[U]]): Try[U]

  5. abstract defforeach[U](f: (T) ⇒ U): Unit

  6. abstract defget: T

  7. abstract defisFailure: Boolean

  8. abstract defisSuccess: Boolean

  9. abstract defmap[U](f: (T) ⇒ U): Try[U]

  10. abstract defrecover[U >: T](f: PartialFunction[Throwable, U]): Try[U]

  11. abstract defrecoverWith[U >: T](f: PartialFunction[Throwable, Try[U]]): Try[U]

Concrete Value Members

  1. final def!=(arg0: AnyRef): Boolean

  2. final def!=(arg0: Any): Boolean

  3. final def##(): Int

  4. final def==(arg0: AnyRef): Boolean

  5. final def==(arg0: Any): Boolean

  6. final defasInstanceOf[T0]: T0

  7. defclone(): AnyRef

  8. final defeq(arg0: AnyRef): Boolean

  9. defequals(arg0: Any): Boolean

  10. deffinalize(): Unit

  11. final defgetClass(): java.lang.Class[_]

  12. defgetOrElse[U >: T](default: ⇒ U): U

  13. defhashCode(): Int

  14. final defisInstanceOf[T0]: Boolean

  15. final defne(arg0: AnyRef): Boolean

  16. final defnotify(): Unit

  17. final defnotifyAll(): Unit

  18. deforElse[U >: T](default: ⇒ Try[U]): Try[U]

  19. final defsynchronized[T0](arg0: ⇒ T0): T0

  20. deftoOption: Option[T]

  21. deftoString(): String

  22. deftransform[U](s: (T) ⇒ Try[U], f: (Throwable) ⇒ Try[U]): Try[U]

  23. final defwait(): Unit

  24. final defwait(arg0: Long, arg1: Int): Unit

  25. final defwait(arg0: Long): Unit

Inherited from AnyRef

Inherited from Any

One thought on “Scala Try Catch Assignment Help

Leave a Reply

Your email address will not be published. Required fields are marked *