alexhelder
03/13/2025, 12:39 AMrunCatching
in a suspend fun
when you are sure the underlying code would not throw CancellationException
(in my case blocking file I/O stuff, FileInputStream
etc)Youssef Shoaib [MOD]
03/13/2025, 12:43 AMCLOVIS
03/13/2025, 3:32 PMrunBlocking
?Youssef Shoaib [MOD]
03/13/2025, 3:57 PMCLOVIS
03/13/2025, 3:57 PMYoussef Shoaib [MOD]
03/13/2025, 3:58 PMrunCatching
might be okay then? Although there's other "fatal" exceptions that shouldn't be caught like OOMs.
Can you give an example of how you're using it? Are you swallowing the exception and printing it or something? That's okay at the top level for instance, but I'd avoid it in something deeply nested because of OOMs and other fatal exceptions existingalexhelder
03/15/2025, 1:07 AMrunCatching
+ CancellationException
issue, but wonder if runCatching
is āsafeā to use inside a coroutine if it is not calling any suspend functions like so (assuming you donāt expect anything thowing Javaās CancellationException
):
suspend fun importNkey(uri: Uri) {
withContext(ioDispatcher) {
readNkeyFromFile2(uri) // plain non-suspend method calls Java blocking I/O stuff
}.onSuccess { nkey ->
dataStore.edit { prefs -> // edit() is a suspend fun
// save in prefs
}
}
}
// not suspend !!!
private fun readNkeyFromFile2(uri: Uri): Result<NKey> =
runCatching {
context.contentResolver.openInputStream(uri)?.use { stream -> // throws IOException, others
stream.bufferedReader().use { reader ->
reader.useLines { lines ->
lines.first { it.startsWith(USER_SEED_PREFIX) } // throws if missing
}
}
} ?: throw IOException() // openInputStream could be null if ContentProvider crashes
}.mapCatching { seed ->
NKey.fromSeed(seed.toCharArray()) // can throw if malformed
}
CLOVIS
03/17/2025, 8:07 AMOutOfMemoryError
. Your code swallows it and tries to continue doing stuff in a half-broken JVM, which may cause further problems down the streamCLOVIS
03/17/2025, 8:07 AMResult
exists to rethrow exceptions elsewhere, NOT for exception recoveryCLOVIS
03/17/2025, 8:08 AMTry
or Either
which are explicitly written to enable these kinds of behaviors