@Throws Annotation in Kotlin


The concept of exception in Kotlin is very much same as it is in Java. All the exceptions in Kotlin are the descendants of the Throwable class. @Throws annotation indicates what exceptions should be declared by a function when compiled to a JVM method.

Example – Throwing exception using a method

In this example, we will create a scenario where we will generate a logical arithmetic exception, but we will try to throw a different exception using the @throws annotation and a function call.

import java.io.*
import kotlin.jvm.Throws

fun main(args: Array<String>) {
   val item=0
   var result=0
   try {
      result=item/0 // Division by Zero Exception
   } catch (ex: Exception) {

      // Although it is Arithmetic exception,
      // we will throw IOException using function call
      ex().throwJavaChecked()
   }
}
class ex{
   @Throws(IOException::class)
   fun throwJavaChecked() {
      throw IOException()
   }
}

Output

On execution, it will produce the following exception −

Exception in thread "main" java.io.IOException
   at ex.throwJavaChecked(main.kt:20)
   at MainKt.main(main.kt:13)

Updated on: 16-Mar-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements