kotlin: supervisorScope和coroutineScope直接子协程的区别

一,区别:

supervisorScope 的直接子协程是可以捕获到异常的,因为这些 supervisorScope 的子协程需要自己处理异常。

与 supervisorScope 不同的是,coroutineScope 的直接子协程不能捕捉到异常

二,例子:supervisorScope的直接子协程可以捕获到异常

代码:

        //处理按钮点击事件
        binding.button3.setOnClickListener {
            runBlocking {
                val handler = CoroutineExceptionHandler { _, e ->
                    println("捕捉到了异常: $e")
                }

                supervisorScope {
                        launch(handler) {
                            println("将要抛出异常")
                            throw Exception("发生了异常")
                        }
                }

            }
        }

运行结果:

image

三,例子:coroutineScope 的直接子协程不能捕捉到异常

代码:

        //处理按钮点击事件
        binding.button2.setOnClickListener {
            runBlocking {
                val handler = CoroutineExceptionHandler { _, e ->
                    println("捕捉到了异常: $e")
                }

                coroutineScope {
                    launch(handler) {
                        println("将要抛出异常")
                        throw Exception("发生了异常")
                    }
                }
            }
        }

运行结果:

image

 

posted @ 2025-08-09 13:41  刘宏缔的架构森林  阅读(9)  评论(0)    收藏  举报