0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

finallyを使用せずに最後の処理を行う方法

Last updated at Posted at 2025-05-03

finallyを使用すれば、try/catchどちらの処理を行っていても必ず最後に実行されます。しかし非同期処理中などでfinallyは使用したくないが、同じ処理を行いたい場合もあると思います。そんな時のテクニックをメモ。

方法:1
tryの中で「こんにちは」の条件に当てはまった時、runブロックを使用してreturnします。デメリットはネストが深くなります。

private fun sayGreeting() {
    var message = ""
    run {
        try {
            message = "おはよう!"
            if (true) {
                // 途中で処理を止めて最後の処理を行いたい
                message = "こんにちは🖐️"
                return@run
            }
            message = "こんばんは..."
        } catch (e: Exception) {
            message = ""
        }
    }
    println(message) // こんにちは🖐️
}

方法:2
単純に同じ処理を複数書きます。処理が少ない場合はこれでもいかなと。デメリットはif文の数だけ同じ処理が増え冗長になります。下記コードdは「sup」が出力されます。

private fun sayGreeting() {
    var message = ""
    try {
        message = "おはよう!"
        if (false) {
            message = "Hello!"
            println(message)
            return
        }

        if (true) {
            message = "sup"
            println(message) // sup
            return
        }

        if (false) {
            message = "hi!"
            println(message)
            return
        }

        message = "こんばんは..."
    } catch (e: Exception) {
        message = ""
        return
    }
    println(message)
}
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?