Can I catch 2 exceptions at once in kotlin like we...
# announcements
v
Can I catch 2 exceptions at once in kotlin like we do in java?
Copy code
// Java code
try {
    return doDangerousThing();
} catch (ExceptionA | ExceptionB e) {
    e.printStackTrace();
}
t
obvious answer : if they both implement the same interface, yes, otherwise ... it's a very good question 🙂
e
maybe no
t
e
No reflection required
Copy code
try {
    return doDangerousThing();
} catch (t: Throwable) {
    when (t) {
        is IOException, is IllegalStateException -> t.printStackTrace()
        else -> throw t
    }
}
But the nasty part is that you have to rethrow or you'd swallow the exception.