Exception is a runtime problem which occurs at the runtime of the program and cause to program termination. This may be happen due to some reason like condition like divided by zero, running out of memory space, array out of bond. We use exception handling to handle this type of problem at the time of program execution. Exception handling is a technique which take care of the runtime problems and keep maintains the flow of program execution. In Kotlin, all exception classes are descendants of sophistication Throwable. To throw an exception object, it uses the throw expression.

These four different keywords used in exception handling. These are:

  • try
  • catch
  • finally
  • throw

try: try block have set of statements which helps to generate an exception. Try block can be use with catch or finally or both.

catch: catch block help us to catch the exception thrown from try block.

finally: finally block is used to run important code statement as we know it always execute whether exception is handled or not. 

throw: throw keyword is helps to throw an exception explicitly.

Kotlin Unchecked Exception

Unchecked exception is a kind of exception which is come out due to mistakes in our code. This type of exception extends RuntimeException class. These exception are checked at run time. Here are some example of unchecked exception:

  • ArithmeticException: thrown when we try to divide a number by zero.
  • ArrayIndexOutOfBoundExceptions: thrown when we try to access incorrect index value at given array.
  • SecurityException: thrown by the security manager which help us to indicate a security violation.
  • NullPointerException: thrown when we try to call a method or property on a null object.

Kotlin try catch

Kotlin try-catch block is employed for exception handling within the code. The try block will enclose the code which can throw an exception and also the catch block is employed to take care the exception. Try block in kotlin must be followed by either catch block or finally block or both.

Syntax of try with catch block

1. try{    
2. //code that may throw exception    
3. }catch(e: SomeException){  
4. //code that handles exception  
5. }  

Syntax of try with finally block

1. try{    
2. //code that may throw exception    
3. }finally{  
4. // code finally block  
5. }   

Syntax of try catch with finally block

1. try {  
2.     // some code  
3. }  
4. catch (e: SomeException) {  
5.     // handler  
6. }  
7. finally {  
8.     // optional finally block  
9. } 

Problem without Exception Handling

Here is an example which causes exception which is not handled.

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

This above program produce an exception, which result 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

Here is the solution of above problem by using try-catch block.

1. fun main(args: Array<String>){  
2.     try {  
3.         val data = 20 / 0  //may throw exception  
4.     } catch (e: ArithmeticException) {  
5.         println(e)  
6.     }  
7.     println("code below exception...")  
8. }  

Output:

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

Kotlin try block as an Expression

We can also use try block as an expression to returns a value. the value which is returned by try expression can be the last expression of try block or the last expression of catch. Contents of the finally block don’t affect the results of the expression.

Kotlin try as an expression example

Here is an example of try-catch block as an expression to returns a value. Here String value to Int which is not capable of generate any exception and returns last statement of try block.

1. fun main(args: Array<String>){  
2. val str = getNumber("10")  
3.     println(str)  
4. }  
5. fun getNumber(str: String): Int{  
6.     return try {  
7.         Integer.parseInt(str)  
8.     } catch (e: ArithmeticException) {  
9.         0  
10.     }  
11. } 

Output:

10

Now modify the above code which help to generate an exception and return the last statement of catch block.

1. fun main(args: Array<String>){  
2. val str = getNumber("10.5")  
3.     println(str)  
4. }  
5. fun getNumber(str: String): Int{  
6.     return try {  
7.         Integer.parseInt(str)  
8.     } catch (e: NumberFormatException) {  
9.         0  
10.     }  
11. } 

Output:

0

Kotlin Multiple catch Block

We can also use multiple catch block in our code. Kotlin multiple catch blocks are mostly used where we are going  to perform different types of operation which may causes different exceptions in try block  with try block .

Kotlin multiple catch block example 1

Here is an example of multiple catch blocks. In this example we will are doing different types of operation. These types of operation may generate different types of exceptions.

1. fun main(args: Array<String>){  
2.     try {  
3.         val a = IntArray(5)  
4.         a[5] = 10 / 0  
5.     } catch (e: ArithmeticException) {  
6.         println("arithmetic exception catch")  
7.     } catch (e: ArrayIndexOutOfBoundsException) {  
8.         println("array index outofbounds exception")  
9.     } catch (e: Exception) {  
10.         println("parent exception class")  
11.     }  
12.     println("code after try catch...")  
13. }  

Output

arithmetic exception catch
code after try catch...

Note: Here at a time only one exception is raised and only one catch block is executed.

Lets see what happen when we catch from general exception to specific exception?

t will produce warning. For example:

Now modify above code and put catch block from general exception to specific exception.

1. un main(args: Array<String>){  
2.     try {  
3.         val a = IntArray(5)  
4.         a[5] = 10 / 0  
5.     }  
6.     catch (e: Exception) {  
7.         println("parent exception catch")  
8.     }  
9.     catch (e: ArithmeticException) {  
10.         println("arithmetic exception catch")  
11.     } catch (e: ArrayIndexOutOfBoundsException) {  
12.         println("array index outofbounds exception")  
13.     }  
14.       
15.     println("code after try catch...")  
16. }  

Output at compile time

warning : division by zero
a[5] = 10/0

Output at run time

parent exception catch
code after try catch...

Kotlin Nested try-catch block

In kotlin we can also  use nested try block whenever required. Nested try catch block is such block within which one try catch block is implemented into another try block. The requirement of nested try catch block is comes when a block of code generates an exception and inside that block another code statements also generates another exception

Syntax of nested try block

2. try    
3. {    
4.     // code block   
5.     try    
6.     {    
7.         // code block   
8.     }    
9.     catch(e: SomeException)    
10.     {    
11.     }    
12. }    
13. catch(e: SomeException)    
14. {    
15. }    

Kotlin nested try block example

1. fun main(args: Array<String>) {  
2.     val nume = intArrayOf(4, 8, 16, 32, 64, 128, 256, 512)  
3.     val deno = intArrayOf(2, 0, 4, 4, 0, 8)  
4.     try {  
5.         for (i in nume.indices) {  
6.             try {  
7.                 println(nume[i].toString() + " / " + deno[i] + " is " + nume[i] / deno[i])  
8.             } catch (exc: ArithmeticException) {  
9.                 println("Can not divided by Zero!")  
10.             }  
11.   
12.         }  
13.     } catch (exc: ArrayIndexOutOfBoundsException) {  
14.         println("Element not found.")  
15.     }  
16. }

Output

4 / 2 is 2
Can not divided by Zero!
16 / 4 is 4
32 / 4 is 8
Can not divided by Zero!
128 / 8 is 16
Element not found.

Kotlin finally Block

Kotlin finally block is a kind of block which is executes whether exception is handled or not. Mostly it is used to execute important code statement.

Kotlin finally Block Example 1

Here is an example of exception handling in which exception does not occur.

1. fun main (args: Array<String>){  
2.     try {  
3.         val data = 10 / 5  
4.         println(data)  
5.     } catch (e: NullPointerException) {  
6.         println(e)  
7.     } finally {  
8.         println("finally block always executes")  
9.     }  
10.     println("below codes...")  
11. }  

Output

2
finally block always executes
below codes...

Kotlin finally Block Example 2

here is an example of exception handling in which exception occurs but not handled.

1. fun main (args: Array<String>){  
2.     try {  
3.         val data = 5 / 0  
4.         println(data)  
5.     } catch (e: NullPointerException) {  
6.         println(e)  
7.     } finally {  
8.         println("finally block always executes")  
9.     }  
10.     println("below codes...")  
11. } 

Output

finally block always executes
Exception in thread "main" java.lang.ArithmeticException: / by zero

Kotlin finally Block Example 3

Here is  an example of exception handling in which exception occurs and handled.

1. fun main (args: Array<String>){  
2.     try {  
3.         val data = 5 / 0  
4.         println(data)  
5.     } catch (e: ArithmeticException) {  
6.         println(e)  
7.     } finally {  
8.         println("finally block always executes")  
9.     }  
10.     println("below codes...")  
11. }  

Output

java.lang.ArithmeticException: / by zero
finally block always executes
below codes...

Kotlin throw keyword

Throw keyword in kotlin is used to throw an explicit exception. It is used to throw a custom exception as well.To throw an exception object we have to use the throw-expression.

Syntax of throw keyword

throw SomeException()  

Here is  an example of throw keyword in which we are validating age limit for driving license.

fun main(args: Array<String>) {  
1.     validate(15)  
2.     println("code after validation check...")  
3. }  
4. fun validate(age: Int) {  
5.     if (age < 18)  
6.         throw ArithmeticException("under age")  
7.     else  
8.         println("eligible for drive")  
9. }

Output

Exception in thread "main" java.lang.ArithmeticException: under age

You may also like...

0 Comments

No Comment.