throws Exception in a method with Kotlin

79,549

Solution 1

In Kotlin, there's no checked exceptions, no exceptions have to be declared and you aren't forced to catch any exception, though, of course, you can. Even when deriving from a Java class, you don't have to declare exceptions that a method throws.

@Throws(SomeException::class) is just intended for Java interoperability, which allows one to write a function with throws in Java signature, so that in Java it will be possible (and necessary) to handle the exception.

Instead, public API exceptions should be documented in KDoc with @throws tag.

Solution 2

In Java your functions are something like this

void foo() throws IOException{
    throw new IOException();
}

But in Kotlin you can add annotation like below to force other Java classes to catch it. However, as other answers have pointed out, it doesn't have any meaning among Kotlin classes.

@Throws(IOException::class)
fun foo() {
    throw IOException()
}

Source kotlinlang.org

Share:
79,549

Related videos on Youtube

cesards
Author by

cesards

Computer Engineer with more than 11 years of experience in the software industry, focused on Android development. Passionate about software architecture, the open-source world, user experience, and user interfaces.

Updated on March 13, 2021

Comments

  • cesards
    cesards about 3 years

    I'm trying to convert this Java code to Kotlin:

    public class HeaderInterceptor implements Interceptor {
      @Override public Response intercept(Chain chain) throws IOException {
        return null;
      }
    }
    

    The problem is, when I implement the methods, I get something like

    class JsonHeadersInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain?): Response? {
            throw UnsupportedOperationException()
        }
    }
    

    The only info I've found talking about throwing exceptions in Kotlin is THIS.

    Apart from removing the question mark, because it's not necessary, why it doesn't handle the IOException the same way? What is the best approach to handle this situation?

    • JB Nizet
      JB Nizet about 8 years
      What do you mean by "handle the IOException"? All exceptions are runtime exceptions in Kotlin, and thus don't need to be declared in the throws clause. And actually, even the Java code doesn't need to declare the IOException in its throws clause, since it never throws any IOException.
  • Mahdi Moqadasi
    Mahdi Moqadasi over 3 years
    I did it in okHttp interceptor. but it didn't force the java callers to catch the IOException. could you please tell me how can I throw exceptions in interceptors?