Last active
December 20, 2015 12:09
-
-
Save yangbajing/6128454 to your computer and use it in GitHub Desktop.
在 try finally 的finally块中访问try中定义变量的一种变通方式。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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