前提
Kotlinを使用してAndroidアプリを作成しています。
IO処理のためcoroutineを使用したいと考えているのですが例外処理に躓いています。
実現したいこと
例外が発生しない時は「終了処理」のみ、例外が発生した場合は「例外処理」と「終了処理」を実行したいと考えています。
下記ソースにて、
- 例外が発生しない場合 ⇒ 実現したい通りに動いています。
- child1で例外が発生した場合 ⇒ 実現したい通りに動いています。
- child2で例外が発生した場合 ⇒ アプリが終了してしまいます。
該当のソースコード
parent
1 override fun onNavigationItemSelected(item: MenuItem): Boolean { 2 when(item.itemId) { 3 // IO 4 R.id.nav_parent -> { 5 parent() 6 } 7 } 8 9 // 選択状態を解除 10 item.isCheckable = false 11 // ドロワーを閉じる 12 drawerLayout.closeDrawers() 13 14 return true 15 } 16 17 private fun parent() { 18 // プログレスバー表示 19 binding.progressBar.visibility = View.VISIBLE 20 21 val handler = Handler(Looper.getMainLooper()) 22 23 var exceptionMessage: String? = "" 24 25 val coroutineScope = CoroutineScope(Job() + Dispatchers.IO) 26 coroutineScope.launch { 27 try { 28 val deferred = coroutineScope.async { 29 30 child1() 31 32 child2() 33 } 34 deferred.await() 35 36 } catch(e: Exception) { 37 exceptionMessage = e.message 38 } finally { 39 handler.post { 40 // プログレスバー非表示 41 binding.progressBar.visibility = View.INVISIBLE 42 43 // メッセージ表示 44 val message = 45 if (exceptionMessage == "") resources.getString(R.string.message_success) 46 else resources.getString(R.string.message_failure) + "\n" + exceptionMessage 47 48 Toast.makeText( 49 this@MainActivity, 50 message, 51 Toast.LENGTH_LONG 52 ).show() 53 } 54 } 55 }
child1
1 fun child1() { 2 // こちらの例外はparentでcatchされる 3 // child2のthrowはコメントアウト 4 throw IOException("child1") 5 }
child2
1 fun child2() { 2 val coroutineScope = CoroutineScope(Job() + Dispatchers.IO) 3 coroutineScope.launch { 4 // こちらの例外がparentでcatchされず、アプリが終了してしまう 5 // child1のthrowはコメントアウト 6 throw IOException("child2") 7 } 8 }
試したこと
child2にて例外の再スローを試行錯誤したのですが上手く動かず悩んでいます。
その他
例外処理はあくまでparentで行いたいと考えています。
Android開発について学習中のため理解が足りていない点は否めず恐縮ではありますが、
ご助力いただきたくよろしくお願いいたします。
あなたの回答
tips
プレビュー