4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Kotlinのエラーハンドリング

Last updated at Posted at 2023-02-01

メモです

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()) {
}

4
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?