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.”
Problem
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.
Solution
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 java.io._ 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 = in.get.read; 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 = inputStream.read; 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.
Discussion
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
newTry()
Abstract Value Members
abstract deffailed: Try[Throwable]
abstract deffilter(p: (T) ⇒ Boolean): Try[T]
abstract defflatMap[U](f: (T) ⇒ Try[U]): Try[U]
abstract defflatten[U](implicit ev: <:<[T, Try[U]]): Try[U]
abstract defforeach[U](f: (T) ⇒ U): Unit
abstract defget: T
abstract defisFailure: Boolean
abstract defisSuccess: Boolean
abstract defmap[U](f: (T) ⇒ U): Try[U]
abstract defrecover[U >: T](f: PartialFunction[Throwable, U]): Try[U]
abstract defrecoverWith[U >: T](f: PartialFunction[Throwable, Try[U]]): Try[U]
Concrete Value Members
final def!=(arg0: AnyRef): Boolean
final def!=(arg0: Any): Boolean
final def##(): Int
final def==(arg0: AnyRef): Boolean
final def==(arg0: Any): Boolean
final defasInstanceOf[T0]: T0
defclone(): AnyRef
final defeq(arg0: AnyRef): Boolean
defequals(arg0: Any): Boolean
deffinalize(): Unit
final defgetClass(): java.lang.Class[_]
defgetOrElse[U >: T](default: ⇒ U): U
defhashCode(): Int
final defisInstanceOf[T0]: Boolean
final defne(arg0: AnyRef): Boolean
final defnotify(): Unit
final defnotifyAll(): Unit
deforElse[U >: T](default: ⇒ Try[U]): Try[U]
final defsynchronized[T0](arg0: ⇒ T0): T0
deftoOption: Option[T]
deftoString(): String
deftransform[U](s: (T) ⇒ Try[U], f: (Throwable) ⇒ Try[U]): Try[U]
final defwait(): Unit
final defwait(arg0: Long, arg1: Int): Unit
final defwait(arg0: Long): Unit
One thought on “Scala Try Catch Assignment Help”