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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…