Exceptions are unwanted issues that can occur at runtime of the program and terminate your program abruptly. Exception handling is a process, using which we can prevent the program from such exceptions that can break our code.
There are two types of exceptions:
1. Checked exceptions that are declared as part of method signature and are checked at the compile time, for example IOException
2. Unchecked exceptions do not need to be added as part of method signature and they are checked at the runtime, for example NullPointerException.
Note: In Kotlin all exceptions are unchecked.
Handling of exception in Kotlin is same as Java. We use try, catch and finally block to handle the exceptions in the kotlin code.
Kotlin Exception handling example
In the following example we are dividing a number with 0 (zero) which should throw ArithmeticException. Since this code is in try
block, the corresponding catch block will execute.
In this case the ArithmeticException occurred so the catch block of ArithmeticException executed and “Arithmetic Exception” is printed in the output.
When an exception occurs, it ignores everything after that point and the control instantly jumps to the catch block if any. The finally block is always executed whether exception occurs or not.
fun main(args: Array<String>) { try { var num = 10/0 println("BeginnersBook.com") println(num) } catch (e: ArithmeticException) { println("Arithmetic Exception") } catch (e: Exception) { println(e) } finally { println("It will print in any case.") } }
Output:
What happens if we don’t handle exception?
Lets say if we don’t handle the exception in the above example then the program would terminate abruptly.
Here we didn’t handle exception so the program terminated with an error.
fun main(args: Array<String>) { var num = 10/0 println("BeginnersBook.com") println(num) }
Output:
How to throw an exception in Kotlin
We can also throw an exception using throw
keyword. In the following example we are throwing an exception using throw keyword. The statement before the exception got executed but the statement after the exception didn’t execute because the control transferred to the catch block.
fun main(args: Array<String>) { try{ println("Before exception") throw Exception("Something went wrong here") println("After exception") } catch(e: Exception){ println(e) } finally{ println("You can't ignore me") } }
Output:
Leave a Reply