https://kotlinlang.org logo
Title
v

vaskir

09/27/2018, 12:16 PM
no
catch (e: MyException if e.foo = 25) { .. }
??
r

robin

09/27/2018, 12:20 PM
Nope. But
catch (e: MyException) {
   if (e.foo == 25) {
   ...
   }
}
works fine.
v

vaskir

09/27/2018, 12:20 PM
🙂
r

robin

09/27/2018, 12:20 PM
...except you'll probably need to rethrow in the else block to imitate your example.
v

vaskir

09/27/2018, 12:23 PM
try {
//    ...
} catch (e: MyException) {
    if (e.code == 25) {
        // do specific stuff
    } else {
        // do common stuff
    }

} catch (e: Exception) {
    // do common stuff
}
so I have to duplicate "do common stuff"
if C#/F# there are guards
like this:
try 
    ...
with 
| :? Exn1 as e when e.bar = 23 -> ...
| FooException(25) -> ...
| _ -> ...
r

robin

09/27/2018, 12:27 PM
That's not really possible in kotlin, unfortunately. If you're already catching
Exception
though, you can do this instead:
try {
//    ...
} catch (e: Exception) {
    if (e is MyException && e.code == 25) {
        // do specific stuff
    } else {
        // do common stuff
    }
}
v

vaskir

09/27/2018, 12:28 PM
ah, this looks better
thanks
r

robin

09/27/2018, 12:30 PM
No problem
Oh and you can of course also use a
when
statement instead if you have more cases to check.