https://kotlinlang.org logo
#getting-started
Title
# getting-started
n

nadi

03/03/2024, 2:11 PM
heyaaa how do i catch multiple exceptions in one line like in java's | operator?
j

Joffrey

03/03/2024, 2:14 PM
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

nadi

03/03/2024, 2:15 PM
ah okie thanks ill go with the when approach them
then*
j

Joffrey

03/03/2024, 2:21 PM
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

Joffrey

03/03/2024, 2:33 PM
It doesn't have to be local, though
e

ephemient

03/03/2024, 2:36 PM
it depends. if you want to early return from the containing function then it can't be non-local
n

nadi

03/03/2024, 2:38 PM
i meant, to use 'when' in another method
s

Stephan Schröder

03/05/2024, 8:38 AM
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

Joffrey

03/05/2024, 8:41 AM
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

Stephan Schröder

03/05/2024, 8:45 AM
@Joffrey too late for that 😂
😭 1
e

ephemient

03/06/2024, 11:15 PM
IMO
runCatching
should really be annotated
@DelicateApi
or something like that. it makes doing the wrong thing far too easy
1
s

Stephan Schröder

03/07/2024, 10:38 AM
though there are usecases where catching Throwable seems to be fine: https://twitter.com/relizarov/status/1299248297849303040
j

Joffrey

03/07/2024, 10:58 AM
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"
5 Views