Just stumpled accross this and though this should ...
# compiler
Just stumpled accross this and though this should be a feature: 1. Optional catch variable
Copy code
try {
    throw Error("Oh no!")
} catch {
    console.log("Something bad happened, but don't know what")
This saves you to write the unneccessary term:
(e: Exception)
(_: Throwable)
2. Elvis operator for exceptions maybe with a excalmation mark
Copy code
var result = methodThatMightThrowAnError() !: return null
If you like it or not it's a very common pattern in libraries to use exceptions as method result. Even though the exception doesn't tell you any thing important it's essential to caputure those exceptions to know that the method didn't succeed. A realworld example would be:
Copy code
inline fun <reified T> validateSignedToken(token: String) =
    try {
    } catch (e: Exception) {
It can be reduced to:
Copy code
inline fun <reified T> validateSignedToken(token: String) =
        Json.decodeFromString<T>(jwtVerifier.verify(token).getClaim("payload").asString()) !: null
And yes it a bit a code golf, but I think this is Kotlin a lot about. Making thinks things very short and concise. When you don't need the Exception why spend writing the type for every try catch block? I can imagine it beeing used in a Unit Testing project as follows:
Copy code
fun insertTokenTest() {
   assertNoException {
      val person = fetchToken() !: "12345678" //This might cause an exception, but when it is not available we just don't mind an use an default value

fun assertNoException(block: () -> Unit) =
    block() !: throw Error("No exception is expected")
I think I have seen this operator already somewhere, but don't know where. Does this already have a name? Otherwise does somebody know a famous person with such a hairdo? ;)
👍 1
Catching all exception types is absolutely a bad idea. It breaks kotlinx.coroutine's cooperative cancellation and can lead to bewildering IO errors with Java's thread interruption.
☝️ 4
👍 1
Kotlin does make common patterns more concise, but it does not (try to) encourage bad practices such as this.
even in unit testing, 1. you don't need
as an exception fails the test to begin with, and 2. you don't want something like this for
because you should always be clear which exception type you are expecting. this is how