メモです
try-catch
val res = try {
    if (Random().nextBoolean()) {
        throw HogeException()
    } else {
        throw FugaException()
    }
} catch (e: HogeException) {
    
} catch (e: FugaException) {
    
} finally {
    
}
runCatching
alsoがfinally相当で使えるが早期リターンが可能
Kotlin 1.5からResult型が返り値に指定できるようになった
val res = runCatching {
    if (Random().nextBoolean()) {
        throw HogeException()
    } else {
        throw FugaException()
    }
}.onSuccess {
}.onFailure {
    when (it) {
        is HogeException -> {
        }
        is FugaException -> {
        }
        else -> {
        }
    }
}.also {
    // ★ここが finally 相当です。(onSuccess や onFailure のブロック内で return しない限りは。)
}
fun hoge(): Result<Nothing> = runCatching {
    if (Random().nextBoolean()) {
        throw HogeException()
    } else {
        throw FugaException()
    }
}
hoge().fold(
    onFailure = {
    },
    onSuccess = {
    }
).also {
    // ★ここが finally 相当です。(onSuccess や onFailure のブロック内で return しない限りは。)
}
hoge().getOrXX()
Either
Arrowライブラリ
https://arrow-kt.io/docs/apidocs/arrow-core/arrow.core/-either/
Exceptionの型を安全にできる
慣例的に右が正常値(Rightのダブルミーニングという説)
fun hoge(): Either<HogeException, Int> =
  if (Random().nextBoolean()) Either.Right(0)
  else Either.Left(HogeException())
val value = hoge()
val res = when(value) {
    is Either.Left -> when (value.value) {
        is HogeException -> {
        }
        else -> "Unknown error"
        }
    }
    is Either.Right -> {
    }
}
fun hoge(): Either<Hoge, Int> =
  Either.catch { throw HogeException() }.mapLeft { Hoge() }
if (hoge().isLeft()) {
}