I'm working on a Java project and within this project I did my first try with Kotlin. I started converting some classes to Kotlin with the JavaToKoltin converter provided in the Intellij Idea. Among others my custom exceptions are now converted to Kotlin. But with this the exception handling does not work correct anymore.
If I throw one of my custom exceptions (e.g. MyCustomKotlinException.kt
) within the java code, the exception is not catched (see code below).
// Example.java package foo import java.util.*; import java.lang.*; import java.io.*; import foo.MyCustomKotlinException; class Example { public static void main (String[] args) { try { // Do some stuff // if Error MyCustomKotlinException e = new MyCustomKotlinException("Error Message"); throw e; } catch (MyCustomKotlinException e) { // <-- THIS PART IS NEVER REACHED // Handle Exception } catch (Throwable e) { e.printStackTrace(); <-- This is catched } finally { // Finally ... } } }
So can anyone explain to me why the exception is not catch. MyCustomKotlinException
is inheriting from Kotlins RuntimeException
, which is just an alias to java.lang.RuntimeException
.
// MyCustomKotlinException.kt package foo class MyCustomKotlinException(err: String) : RuntimeException(err)
Update:
I split the throw part into 2 lines (instance creation and throwing) and found that the problem is not the throwing. The try block is left after the instance creation. Is anything wrong with my instance creation of this Kotlin class?
Update2:
I added a second catch block with Throwable
and the following Throwable is caught.
java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics ... Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics
Update3:
Changed the title to correct error and fixed problem with adding all project files to jar (see answer below). Adding the Kotlin runtime lib to gradle does not work for me.
Adding all project files to the jar fixed the problem for me. I added the following line to my build.gradle
jar { manifest { attributes ... } // This line of code recursively collects and copies all of a project's files // and adds them to the JAR itself. One can extend this task, to skip certain // files or particular types at will from { configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) } } }
Update: Changed configurations.compile.collect
to configurations.compileClasspath.collect
according to this answer below.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With