Force android studio compiler to use try-catch when using @Throws - Kotlin

1.2k Views Asked by At

In Java, Android Studio has a feature to avoid calls to methods that throws exception without try/catch blocks and its auto-complete suggests to: Add exception to method signature or Surround with try/catch.

But in Kotlin we don't have throws keyword and should use @Throws() instead. The problem is that Android Studio is no longer forcing us to surround with try/catch. On the other hand it does not force us to use try/catch for java methods that throws Exception like IO progresses.

Test.java

public class Test {

    public void doSomeWork1(int a) throws Exception {
        if (a == -1) {
            throw new Exception("some error");
        }
    }

    public void main() {
        doSomeWork1(-1);
    }
}

Test.kt

class Test {

    @Throws(Exception::class)
    fun doSomeWork1(a: Int) {
        if (a == -1) {
            throw Exception("some error")
        }
    }

    fun main() {
        doSomeWork1(-1)
    }
}

Test.java

Test.java class that android studio not allowing us to compile my code without using try catch.

Test.kt

Test.kt class that is compiling without an error.

android studio auto-complete suggestions

Test.java android studio auto-complete suggestions

Is there any way to force android studio for kotlin language to use try/catch for these functions/methods or at least gives us a warning?

0

There are 0 best solutions below