Implicit type for catch all block


#1

Quite often we’re not interested in distinguishing types of exceptions in catch block, we just catch whatever comes and either log it, provide some default value etc.
I think it would be useful to be able to omit exception type in such case and just write catch(e) and have type of e implicitly set to Throwable

This would be especially useful when using try catch as single line expressions (like for example in: val str = try { readFile() } catch(e) { defaultContent } - I can’t see any drawback of omitting “:Throwable” in this case - or is there any that I’m not aware of?


#2

I see just one drawback: adding unnessessary feature to language. If this case is common in your code you can just create a function like
inline fun <T> tryOrDefault(default: T, block: () -> T) = try { block() } catch (e: Throwable) { default }


#3

I’m not sure if you can call it a feature, rather simplification :slight_smile: - same as I don’t need to explicitly type parameters in lambda or variables


#4

This design seems like it would only encourage swallowing exceptions, which is an anti-pattern (at the very least, we should always be logging them).


#5

@nanodeath Nothing prevents swallowing exceptions now with the explicit Throwable type specified.


#6

@Antoni.Mysliborski The similar request is already filed as https://youtrack.jetbrains.com/issue/KT-17957, feel free to vote for it or provide your use case there, if it’s not already listed.


#7

@ilya.gorbunov I agree that having explicit Throwable type doesn’t change too much in terms of not swallowing.
I added my comment there and voted, thanks for pointing it out