Industrial Training




Kotlin try catch


Kotlin try-catch block is used for exception handling in the code. The try block encloses the code which may throw an exception and the catch block is used to handle the exception. This block must be written within the method. Kotlin try block must be followed by either catch block or finally block or both.


Syntax of try with catch block


try{    
//code that may throw exception    
}catch(e: SomeException){  
//code that handles exception  
}    
try{    
//code that may throw exception    
}catch(e: SomeException){  
//code that handles exception  
}    
Syntax of try with finally block

try{    
//code that may throw exception    
}finally{  
// code finally block  
}    
try{    
//code that may throw exception    
}finally{  
// code finally block  
}    

Syntax of try catch with finally block


try {  
    // some code  
}  
catch (e: SomeException) {  
    // handler  
}  
finally {  
    // optional finally block  
}  
try {  
    // some code  
}  
catch (e: SomeException) {  
    // handler  
}  
finally {  
    // optional finally block  
}  

Problem without Exception Handling


Lets's see an example which causes exception which is not handled.


fun main(args: Array< String>){  
    val data = 20 / 0   //may throw exception  
    println("code below exception ...")  
}  
fun main(args: Array< String>){  
    val data = 20 / 0   //may throw exception  
    println("code below exception ...")  
}  			  

This above program generates an exception, which causes rest of code below the exception not executable.


Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at ExceptionHandlingKt.main(ExceptionHandling.kt:2)

Solution by exception handling


Let's see the solution of above problem by using try-catch block.


fun main(args: Array< String>){  
    try {  
        val data = 20 / 0  //may throw exception  
    } catch (e: ArithmeticException) {  
        println(e)  
    }  
    println("code below exception...")  
}  
fun main(args: Array< String>){  
    try {  
        val data = 20 / 0  //may throw exception  
    } catch (e: ArithmeticException) {  
        println(e)  
    }  
    println("code below exception...")  
}  

Output:
java.lang.ArithmeticException: / by zero
code below exception...

In the above program after implementing try - catch block, rest of code below exception executes.


Kotlin try block as an Expression


We can use try block as an expression which returns a value. The value returned by try expression is either the last expression of try block or the last expression of catch. Contents of the finally block do not affect the result of the expression.


Kotlin try as an expression example


Let's see an example of try-catch block as an expression which returns a value. In this example String value to Int which does not generate any exception and returns last statement of try block.


fun main(args: Array< String>){  
val str = getNumber("10")  
    println(str)  
}  
fun getNumber(str: String): Int{  
    return try {  
        Integer.parseInt(str)  
    } catch (e: ArithmeticException) {  
        0  
    }  
}  
fun main(args: Array< String>){  
val str = getNumber("10")  
    println(str)  
}  
fun getNumber(str: String): Int{  
    return try {  
        Integer.parseInt(str)  
    } catch (e: ArithmeticException) {  
        0  
    }  
}  

Output:
10

Let's modify the above code which generate an exception and return the last statement of catch block.


fun main(args: Array< String>){  
val str = getNumber("10.5")  
    println(str)  
}  
fun getNumber(str: String): Int{  
    return try {  
        Integer.parseInt(str)  
    } catch (e: NumberFormatException) {  
        0  
    }  
}  
fun main(args: Array< String>){  
val str = getNumber("10.5")  
    println(str)  
}  
fun getNumber(str: String): Int{  
    return try {  
        Integer.parseInt(str)  
    } catch (e: NumberFormatException) {  
        0  
    }  
}  

Output:
0


Hi I am Pluto.