简体   繁体   中英

Why is getMessage() an unresolved reference in Kotlin with an Exception class?

Kotin documentation says that "All exception classes in Kotlin are descendants of the class Throwable. Every exception has a message, stack trace and an optional cause."

The Java documentation for Throwable shows a getMessage() method. But the Kotlin documentation for Throwable does not have a getMessage(). So this code:

fun main(args: Array<String>)
{
   try
   {
      println("args size: ${args.size}");
   }
   catch (e: Exception)
   {
      println(e.getMessage())
      System.exit(1)
   }
}

gives me this compile error:

test_exception.kt:12:17: error: unresolved reference: getMessage
      println(e.getMessage())
                ^

suggesting that I am using a Kotlin Exception class derived from a Kotlin Throwable class.

However, if I change getMessage() to toString() and add a throw:

fun main(args: Array<String>)
{
   try
   {
      println("args size: ${args.size}");
      throw Exception("something went wrong")
   }
   catch (e: Exception)
   {
      println(e.toString())
      System.exit(1)
   }
}

I get this message:

java.lang.Exception: something went wrong

Which seems to say that the Exception class is NOT a Kotlin Exception class - but the java version which has a getMessage() method and I shouldn't get a compile error when I try to use it.

There is no other Throwable except for java.lang.Throwable . This class is used both by Java and by Kotlin programs.

The fact that Throwable has an entry in the Kotlin documentation suggests that this is a special compiler "alias". That means that for all intents and purposes it is a Kotlin class, instances of which are represented by java.lang.Throwable . Black magic.

TL;DR:

The equivalent of e.getMessage() in Kotlin is e.message , which is described in the docs as open val message: String? .

Since Throwable is not used directly from Java, but mapped to Kotlin, you cannot use the Java notation e.getMessage() for the property. Here is more about mapped types: http://kotlinlang.org/docs/reference/java-interop.html#mapped-types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM