Does Kotlin have multi-catch?

Is there an issue that we can vote for to get this in?

9 Likes

Yes - https://youtrack.jetbrains.com/issue/KT-7128

It seems very odd that after 4 years this issue is still awaiting prioritisation.

I get that exceptions are not ‘cool’ from a functional perspective, but Kotlin is a General Purpose language, and allow succinct code in the main programming styles.

8 Likes

Maybe they are actively considering union types, in which case multi-catch would follow for free.

4 Likes

And this is the final wish:

try {
    // code
} catchWhen(ex:Exception) {
        is SomeException,
        is AnotherException -> {
            // handle
        }
        else -> throw ex
}
4 Likes

I also encountered situation for multi catch today and landed here.
Sadly, I see lot of people already reported this, and no action taken till now.

2 Likes

@yole as it’s been awhile since last reply, I am wondered if there any foreseen time-line for implementing this feature?

As probably already stated in this thread, not supporting checked exceptions and, nevertheless, multi-catch is a design choice. To better understand the problems of checked exceptions and whatever construct derivates from it, I recommend this post from @elizarov. His blog is a great source for understanding many design choices of Kotlin!

Not having multi-catch has nothing to do with not having checked exceptions. Both approaches are orthogonal to each other.

I think you meant that multi catch and checked exceptions have nothing to do with each other :wink:
That said, if you follow the coding guidelines provided in the link you don’t have much use for multi catch. Still it would be a nice feature to have.

1 Like

Read the article fully…

Posting this comment for visibility.

It’s astonishing that after 6 years and over 300 likes on https://youtrack.jetbrains.com/issue/KT-7128 this feature still hasn’t been added.

1 Like

lol read the article 4 messages above :laughing:

Just created my own implementation for that…

This is how it looks like:

        unsafe {
            danger {
                // place some danger code that probably throws an exception.. (placed in try-Block)
            }
        
            except(ConnectException::class, SocketException::class) {
                // catch code for either ConnectException or SocketException
            }
        
            except(NullPointerException::class) {
                // multiple catch blocks possible
            }
        }

The implementation of the Unsafe-Class is on Github: