- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
@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)
Advertisements