0 votes
in Kotlin by
Explain Exception Handling in Kotlin

1 Answer

0 votes
by

Exception in programming is defined as a runtime problem which occurs in the program, leading it to terminate. This issue can occur due to less memory space, array out of bond, conditions like division by zero. To curb these types of issues in code execution, exception handling is used.

Exception handling is defined as the technique which handles the runtime problems and also maintains the program flow during execution.

Kotlin uses the ‘throw’ expression to throw an exception object. Here all exception classes are descendants of class Throwable.

Throw MyException(“throws exception”)

There are four types of exceptions in exception handling. They are:

  • try – This block contains statements which might create the exception. It is always followed by either catch or finally or both.
  • catch – it catches an exception thrown from the try block.
  • finally – It always checks whether the exception is handled or not.
  • throw – It is used to throw an exception explicitly.

Try catch:

In try-catch block in exception handling, try block encloses the code, which may throw an exception and catch block catches the expression and handles it.

Syntax of try catch block:

try{    
//code with exception    
}catch(e: SomeException){  
//code handling exception  
}    

Syntax of try with finally block

try{    
//code with exception    
}finally{  
// code finally block  
}   

Finally:

In Kolin, finally block always checks whether the exception is handled or not, making it a very important statement of exception handling.

For Example 4:

In this code snippet, the exception occurs, and it is handled.

fun main (args: Array<String>){  
    try {  	
        val data =  9/ 0  
        println(data)  
    } catch (e: ArithmeticException) {  
        println(e)  
    } finally {  
        println("finally block executes")  
    }  
    println("write next code")  
}  

Output:

java.lang.ArithmeticException: / by zero
finally block executes
write next code

Throw:

Throw block throws an explicit exception. Moreover, it is used to throw custom exceptions.

Syntax:

Throw SomeException()

Throw SomeException()

Example:

fun main(args: Array<String>) {
    try{
        println("Exception is not thrown yet")
        throw Exception("Everything is not well")
        println("Exception is thrown")
    }
    catch(e: Exception){
        println(e)

    }
    finally{
        println("You can't ignore me")
    }
}

Output:

Kotlin tutorial

Related questions

0 votes
asked May 26, 2022 in Kotlin by Robin
0 votes
0 votes
asked May 26, 2022 in Kotlin by Robin
0 votes
0 votes
asked May 26, 2022 in Kotlin by Robin
...