In the last tutorial we learned what is an exception handling. In this guide we will see various examples of try catch block. We will also see how to use try as an expression.
Syntax of try catch block
try { //code where an exception can occur } catch (e: SomeException) { // handle the exception } finally { // optional block but executes always }
A try block can be associated with more than one catch blocks, however there can be only one finally block present.
Kotlin try catch block example
In this example we have placed the code that can cause exception inside try block. Once the exception occurs inside try block, it looks for the corresponding catch block where the occurred exception is handled. Since in the code ArithmeticException is occurred and the same exception is handled in the catch block, the code inside catch block is executed.
The main advantage of exception handling is that the program doesn’t terminate abruptly. In the following example the last println statement println("Out of try catch block")
is executed after catch block. If we didn’t have exception handling in place then this statement wouldn’t be executed as the program would have been terminated on the line var num = 100/0
fun main(args: Array<String>) { try{ var num = 100/0 println(num) } catch(e: ArithmeticException){ println("Arithmetic Error in the code") } println("Out of try catch block") }
Output:
Kotlin try block with no catch blocks
A try block can have no catch blocks but in that case a finally block must be present. In short you can say that at least one catch or finally block should be present. Finally block is optional but when there are no catch blocks present, it is must to have a finally block.
fun main(args: Array<String>) { try{ var num = 10/5 println(num) } finally{ println("Finally block") } println("Out of try catch block") }
Output:
2 Finally block Out of try catch block
Leave a Reply