George
11/09/2022, 5:54 PMrunCatching
in cases where we care about only one type of exception or is this too much neatpicking?
For example:
val result = runCatching { transaction() }
return result.getOrElse {
if (it is IllegalArgumentException) return null else throw it
}
vs
return try {
transaction()
} catch (e: IllegalArgumentException) {
null
}
Thanks in advance for any answers !George
11/09/2022, 5:55 PMResult.kt
type since it is a value class.Paul Griffith
11/09/2022, 5:56 PMrunCatching
if you only care about a single type of exceptionJoffrey
11/09/2022, 5:57 PMrunCatching
because it also catches errors (StackOverflowError
, NoClassDefFoundError
, OutOfMemoryError
, and the likes), which you really don't want to catch most of the time.Joffrey
11/09/2022, 5:58 PMIllegalArgumentException
. This exception is generally used to indicate a bug in your code (like a function used inappropriately). You should instead fix the code that generates this exception, and not catch at all.ephemient
11/09/2022, 6:03 PMResult
(and runCatching
by extension) is when you are always definitely going to rethrow that exception. this is true for all the coroutines machinery that uses Result
internally, but rarely for any non-framework code and definitely not hereephemient
11/09/2022, 6:04 PMephemient
11/09/2022, 6:07 PMnull
or some other signal instead of throwing. but if your API is poor, you may have no choice but to catch. in that case, do the second optionephemient
11/09/2022, 6:10 PMResult
is a value class, it does still box primitives and put extra wrapping around exceptions, because that's the only reasonable way for it to be implemented on JVM (at least until Valhalla)George
11/09/2022, 6:35 PMinternal inline fun <T> runRecoveringTransaction(transaction: () -> T?): T? {
val result = runCatching { transaction() }
return result.getOrElse {
if (it is DataIntegrityViolationException) return null else throw it
}
}
Which throws in case of other exceptions should i refactor it?
Also, if this code ends up in your code review, how much weight you would put for the refactoring to be made?Paul Griffith
11/09/2022, 6:41 PMephemient
11/09/2022, 6:41 PMephemient
11/09/2022, 6:43 PMtry
-catch
is idiomatic