Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Try(private val block: () -> Unit,
- private val catchHandler: ((Exception) -> Unit)?)
- : () -> Unit {
- constructor(block: () -> Unit): this(block, null) {}
- fun whenThrown(catchHandler: (Exception) -> Unit): Try {
- return Try(this, catchHandler)
- }
- override operator fun invoke() {
- try {
- block.invoke()
- } catch (e: Exception) {
- val handler = catchHandler ?: throw e
- handler(e)
- }
- }
- }
- fun main(args: Array<String>) {
- Try {
- println("one")
- throw RuntimeException("oops")
- }.whenThrown { e ->
- println("two got error $e")
- throw IllegalStateException("nope")
- }.whenThrown { e ->
- println("three got error $e")
- throw IllegalArgumentException("neither")
- }.invoke()
- }
Add Comment
Please, Sign In to add comment