heyaaa how do i catch multiple exceptions in one l...
# getting-started
n
heyaaa how do i catch multiple exceptions in one line like in java's | operator?
j
Kotlin doesn't have a multi-catch operator. So you'd have to either repeat the handling code, or catch
Exception
and use a
when
in the catch block. But honestly if you need to do something more than a one liner I'd suggest extracting a function anyway.
n
ah okie thanks ill go with the when approach them
then*
j
Usually the
when
approach will lead to more nesting and boilerplate than a simple function and 2 different catch blocks. Because if you have a
when
you also should have an
else
that rethrows everything you don't handle: See:
Copy code
try {
   // Main code
} catch(e: Exception) {
    when(e) {
        is Exception1,
        is Exception2 -> {
            // Complex
            // Error
            // Handling
        }
        else -> throw e
    }
}
VS
Copy code
try {
    // Main code
 } catch(e: Exception1) {
     handleError(e)
 } catch(e: Exception2) {
     handleError(e)
 }
 
private fun handleError(e: Exception) {
     // Complex
     // Error
     // Handling
}
j
It doesn't have to be local, though
e
it depends. if you want to early return from the containing function then it can't be non-local
n
i meant, to use 'when' in another method
s
since your question didn't say that you wanted to catch multiple exceptions within a try-catch block, the functional way to do this is to use runCatching which returns a Result.
j
Please don't, you would be catching way way more than necessary, even `Error`s. This is not meant to be used in business code
☝️ 2
s
@Joffrey too late for that 😂
😭 1
e
IMO
runCatching
should really be annotated
@DelicateApi
or something like that. it makes doing the wrong thing far too easy
1
s
though there are usecases where catching Throwable seems to be fine: https://twitter.com/relizarov/status/1299248297849303040
j
It can be fine in business code for rethrowing with a cause. Framework code that need a catch-all for reporting/crash handling is also ok. Most business code shouldn't. By definition of the
Error
class, "reasonable applications shouldn't try to catch them"