- Trending Categories
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
How to catch many exceptions at the same time in Kotlin?
Exception handling is an important feature of any programming language. It restricts our programs from generating incorrect output at runtime. Kotlin does not support throwing multiple exceptions at the same time, however we can implement this functionality using some other functions provided by the Kotlin library.
Example – Throwing Multiple Exceptions
In this example, we will try to generate an arithmetic exception at runtime and we will try to catch the same in the catch block along with other different exception checks.
fun main(args: Array<String>) { val item=0 var result=0 try { result=item/0 // Exception: Division by Zero } catch (ex: Exception) { when(ex) { // inlcude multiple exceptions here is IllegalAccessException, is IndexOutOfBoundsException -> { println(ex) } is ArithmeticException ->{ println(ex) } else-> throw ex } } }
Output
Here, we are throwing multiple exceptions at the catch block. It will produce the following output −
java.lang.ArithmeticException: / by zero
Advertisements