Guest User

Untitled

a guest
Feb 20th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. class Try(private val block: () -> Unit,
  2. private val catchHandler: ((Exception) -> Unit)?)
  3. : () -> Unit {
  4.  
  5. constructor(block: () -> Unit): this(block, null) {}
  6.  
  7. fun whenThrown(catchHandler: (Exception) -> Unit): Try {
  8. return Try(this, catchHandler)
  9. }
  10.  
  11. override operator fun invoke() {
  12. try {
  13. block.invoke()
  14. } catch (e: Exception) {
  15. val handler = catchHandler ?: throw e
  16. handler(e)
  17. }
  18. }
  19.  
  20. }
  21.  
  22.  
  23. fun main(args: Array<String>) {
  24. Try {
  25. println("one")
  26. throw RuntimeException("oops")
  27. }.whenThrown { e ->
  28. println("two got error $e")
  29. throw IllegalStateException("nope")
  30. }.whenThrown { e ->
  31. println("three got error $e")
  32. throw IllegalArgumentException("neither")
  33. }.invoke()
  34. }
Add Comment
Please, Sign In to add comment