Repository: Kotlin/kotlinx.coroutines
File: kotlinx-coroutines-core/jvm/src/internal/CoroutineExceptionHandlerImpl.kt (Kotlin)

Code before:
 * Note that Android may have dummy [Thread.contextClassLoader] which is used by one-argument [ServiceLoader.load] function,
 * see (https://stackoverflow.com/questions/13407006/android-class-loader-may-fail-for-processes-that-host-multiple-applications).
 * So here we explicitly use two-argument `load` with a class-loader of [CoroutineExceptionHandler] class.
 *
 * We are explicitly using the `ServiceLoader.load(MyClass::class.java, MyClass::class.java.classLoader).iterator()`
 * form of the ServiceLoader call to enable R8 optimization when compiled on Android.
 */
internal actual val platformExceptionHandlers: Collection<CoroutineExceptionHandler> = ServiceLoader.load(
    CoroutineExceptionHandler::class.java,
    CoroutineExceptionHandler::class.java.classLoader
).iterator().asSequence().toList()

internal actual fun ensurePlatformExceptionHandlerLoaded(callback: CoroutineExceptionHandler) {
    // we use JVM's mechanism of ServiceLoader, so this should be a no-op on JVM.
    // The only thing we do is make sure that the ServiceLoader did work correctly.
    check(callback in platformExceptionHandlers) { "Exception handler was not found via a ServiceLoader" }
}

internal actual fun propagateExceptionFinalResort(exception: Throwable) {
    // use the thread's handler
    val currentThread = Thread.currentThread()
    val exceptionHandler = currentThread.uncaughtExceptionHandler
    try {
        exceptionHandler.uncaughtException(currentThread, exception)
    } catch (_: Throwable) {
        /* Do nothing.
         * From https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Thread.UncaughtExceptionHandler.html :
         * > Any exception thrown by this method will be ignored by the Java Virtual Machine.
         *
         * This means the authors of the thread exception handlers have the right to throw exceptions indiscriminately.
         * We have no further channels for propagating the fatal exception, so we give up. */
    }
}

// This implementation doesn't store a stacktrace, which is good because a stacktrace doesn't make sense for this.
internal actual class DiagnosticCoroutineContextException actual constructor(context: CoroutineContext) : RuntimeException() {

    @Transient
    private val context: CoroutineContext? = context

    override fun getLocalizedMessage(): String {
        return context.toString()
    }

    override fun fillInStackTrace(): Throwable {
        // Prevent Android <= 6.0 bug, #1866
        stackTrace = emptyArray()
        return this
    }
}


Review comment (suggestion):
Shall we also add a sample?

```
val handler = CoroutineExceptionHandler { _, e ->
    // e is IllegalStateException("Will be handled")
    throw IllegalStateException("Will be thrown and ignored")
}
GlobalScope.launch(handler) {
    throw IllegalStateException("Will be handled")
}.join()
println("This sample finishes successfully, without any exceptions.")
```

Code after:
 * Note that Android may have dummy [Thread.contextClassLoader] which is used by one-argument [ServiceLoader.load] function,
 * see (https://stackoverflow.com/questions/13407006/android-class-loader-may-fail-for-processes-that-host-multiple-applications).
 * So here we explicitly use two-argument `load` with a class-loader of [CoroutineExceptionHandler] class.
 *
 * We are explicitly using the `ServiceLoader.load(MyClass::class.java, MyClass::class.java.classLoader).iterator()`
 * form of the ServiceLoader call to enable R8 optimization when compiled on Android.
 */
internal actual val platformExceptionHandlers: Collection<CoroutineExceptionHandler> = ServiceLoader.load(
    CoroutineExceptionHandler::class.java,
    CoroutineExceptionHandler::class.java.classLoader
).iterator().asSequence().toList()

internal actual fun ensurePlatformExceptionHandlerLoaded(callback: CoroutineExceptionHandler) {
    // we use JVM's mechanism of ServiceLoader, so this should be a no-op on JVM.
    // The only thing we do is make sure that the ServiceLoader did work correctly.
    check(callback in platformExceptionHandlers) { "Exception handler was not found via a ServiceLoader" }
}

internal actual fun propagateExceptionFinalResort(exception: Throwable) {
    // use the thread's handler
    val currentThread = Thread.currentThread()
    val exceptionHandler = currentThread.uncaughtExceptionHandler
    try {
        exceptionHandler.uncaughtException(currentThread, exception)
    } catch (_: Throwable) {
        /* Do nothing.
         * From https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Thread.UncaughtExceptionHandler.html :
         * > Any exception thrown by this method will be ignored by the Java Virtual Machine.
         *
         * This means the authors of the thread exception handlers have the right to throw exceptions indiscriminately.
         * We have no further channels for propagating the fatal exception, so we give up. */
        val breakpoint = "Put a breakpoint here"
    }
}

// This implementation doesn't store a stacktrace, which is good because a stacktrace doesn't make sense for this.
internal actual class DiagnosticCoroutineContextException actual constructor(context: CoroutineContext) : RuntimeException() {

    @Transient
    private val context: CoroutineContext? = context

    override fun getLocalizedMessage(): String {
        return context.toString()
    }

    override fun fillInStackTrace(): Throwable {
        // Prevent Android <= 6.0 bug, #1866
        stackTrace = emptyArray()
        return this
    }
}