Skip to content

Instantly share code, notes, and snippets.

@yangbajing
Last active December 20, 2015 12:09
Show Gist options
  • Save yangbajing/6128454 to your computer and use it in GitHub Desktop.
Save yangbajing/6128454 to your computer and use it in GitHub Desktop.
在 try finally 的finally块中访问try中定义变量的一种变通方式。
package demo
import java.io.{IOException, FileOutputStream}
object TryCatchFinally {
def trying[T, R](
in: => T,
func: T => R,
catchFunc: Throwable => R,
finallyFunc: T => Unit): R = {
var value: Option[T] = null
try {
value = Option(in)
func(value.get)
} catch {
case e: Throwable =>
catchFunc(e)
} finally {
value.foreach(finallyFunc)
}
}
def tryoption[R](func: => R): Option[R] =
try {
val ret = func
Option(ret)
} catch {
case _: Throwable =>
None
}
def tryeither[R](func: => R): Either[Throwable, R] =
try {
val ret = func
Right(ret)
} catch {
case e: Throwable =>
Left(e)
}
def tryfinally[T, R](in: => T, func: T => R, finallyFunc: T => Unit): R = {
var value: Option[T] = None
try {
value = Option(in)
func(value.get)
} finally {
value.foreach(finallyFunc)
}
}
// 注意有多个变量时finally的不同
def tryfinally[A, B, R](in1: => A, in2: => B, func: (A, B) => R, finallyFunc: (Option[A], Option[B]) => Unit): R = {
var a: Option[A] = None
var b: Option[B] = None
try {
a = Option(in1)
b = Option(in2)
func(a.get, b.get)
} finally {
finallyFunc(a, b)
}
}
def main(args: Array[String]) {
val ret =
trying[FileOutputStream, Int](
new FileOutputStream("/tmp/ttt.txt"),
out => {
val msg = "中华人民共和国".getBytes("UTF-8")
out.write(msg)
msg.length
},
_ => -1,
_.close()
)
println(s"已向文件文件写入:${ret} 字节。")
// 将抛出异常
tryfinally[FileOutputStream, Int](
new FileOutputStream("/tmp/ttt.txt"),
out => {
val msg = "中华人民共和国".getBytes("UTF-8")
out.write(msg)
throw new RuntimeException()
msg.length
},
t => {
println("已关闭文件资源")
t.close()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment