How to throw generic exception

Hi guys,

could anybody show me how to convert that Java code to Kotlin?

public <E extends Throwable> void foo() throws E

And before you have to ask: “throws Throwable” is no option because that method is called from Java legacy code. And that Java code only catches “E”…

1 Like

You cannot declare a method with such Java signature in Kotlin, so if you want to preserve ability to invoke it from Java with this particular signature, then the best thing you can do is to declare it in Java. You can still implement it in Kotlin, though, either via delegation or via override.

Thanks for your fast reply. I switched back to Java for these classes.

Any idea if this feature will be added in the future?

Kotlin does not have checked exceptions and is unlikely to introduce Java-style checked exceptions (where a specific classes of checked exceptions that are thrown by the method are declared) which are needed to port this specific signature to Kotlin. One might ask for an extension of Kotlin’s Throws annotation to support your use-case, though, and there is a similar issue in YouTrack that you can watch:

1 Like