1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fun mainFunction() {
try {
val t = thread(start = false) {
Thread.sleep(1000)
throw IllegalStateException("!!!!!")
}.apply {
setUncaughtExceptionHandler { thread, throwable ->
println("child" + throwable.message)
}
start()
}

} catch (e: Exception) {
println("Main" + e.message)
}
println("end")
}

fun main() {
mainFunction()
}

最终输出是:

1
2
end
child!!!!!

try catch不能捕获在trycatch括号内开的子线程抛出的异常,可以为线程设置一个 UncaughtExceptionHandler

我联想到Coroutine中,try catch同样无法捕获括号内新开的子协程内抛出的错误,与之不同的是,协程的错误不是定义子协程的exception handler来处理,而是可以为TopLevelScope或Top level coroutine定义异常处理器。

参考资料:

以前写的协程异常处理

Java多线程捕获