@Throws does not work when the target is a property

Looking at this question , I noticed that applying @Throwsto getor sethas no effect.

Further, only valid for purposes @Throwsare AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTERand AnnotationTarget.CONSTRUCTOR.

Other annotations, such as and JPA annotations Deprecated, work great and apply to the method!

This is a weird behavior.

To demonstrate, I created a simple abstract class in Java, with one constructor, one method, and one get method.

public abstract class JavaAbstractClass {

    @Deprecated
    @NotNull public abstract String getString() throws IOException;
    public abstract void setString(@NotNull String string) throws IOException;

    public abstract void throwsFunction() throws IOException;

    public JavaAbstractClass() throws IOException {
    }

}

As you can see, each method / constructor is marked as metaling IOException.

, Kotlin throws interop, getString setString throws.

abstract class KotlinAbstractClass @Throws(IOException::class) constructor() {

    @get:Deprecated("Deprecated")
    @get:Throws(IOException::class)
    @set:Throws(IOException::class)
    abstract var string: String

    @Throws(IOException::class)
    abstract fun throwsFunction()

}

:

@Metadata(Some metadata here)
public abstract class KotlinAbstractClass {
   /** @deprecated */
   @Deprecated(
      message = "Deprecated"
   ) // @Deprecated made it through!
   @NotNull
   public abstract String getString(); // Nothing here!

   public abstract void setString(@NotNull String var1); // Nothing here!

   public abstract void throwsFunction() throws IOException;

   public KotlinAbstractClass() throws IOException {
   }
}

, , , , .

, :

val string: String
@Throws(IOException::class) get() = "Foo"

public final String getString() throws IOException!

, ?

?


. , .

:

@get:Throws(IOException::class)
val string: String
    get() = BufferedReader(FileReader("file.txt")).readText()

-

@NotNull
public final String getString() {
    return TextStreamsKt.readText((Reader)(new BufferedReader((Reader)(new FileReader("file.txt")))));
}

, FileReader FileNotFoundException.

, , throws.

@tynn, :

class ConcreteClass : KotlinAbstractClass() {

    override val string: String
        get() = BufferedReader(FileReader("file.txt")).readText()

    ...

}

.

+4
1

, @tynn :

override val string: String
        @Throws(FileNotFoundException::class) get() = BufferedReader(FileReader("file.txt")).readText()

Java throws . , , :

@get:Throws(IOException::class)
val foo: String = "foo"

, , , IOException, , throws. , , , , , throws.

UPDATE

, -:

abstract class KotlinAbstractClass {

    abstract var string: String
        @Throws(IOException::class) get
        @Throws(IOException::class) set
}

, @get:Throws(IOException::class) . YouTrack Kotlin , .

+2

Source: https://habr.com/ru/post/1690507/


All Articles