Exception Handling in Kotlin with Examples

Exceptions are the error which comes at the runtime and disrupts your flow of execution of the program. Basically exception is the unwanted event that occurs at runtime. The method by which we can handle this kind of error is called Exception Handling.

Types of Exceptions

  1. Checked Exception: Exceptions that occur at the compile-time, or we can say that checked at the compile time is called Checked Exception. Example — IOException, Some file related Exception, etc
  2. Unchecked Exception: Exceptions that occur at the runtime is called Unchecked Exception. Example — OutofBound exception.

Note: In Kotlin we have only unchecked Exceptions which only figure out at the runtime.

How to Handle Exceptions?

We have some keywords which help us to handle Exceptions.

  1. Try            // This will try to find the exception
  2. Throw      // If exception found then it will throw the exception
  3. Catch       // After throwing it will catch the exception and execute their body.

We have one more keyword called Finally, It will always execute either we got exception or not. In this, we have some important codes that always need to execute.

Note: If the program exit by exitProcess(Int) or abort(), then the finally will not be executed.



How to Use try-catch and finally?

filter_none

edit
close

play_arrow

link
brightness_4
code

try
{
  // your code which
  // may throw an exception
}
catch(ex : ExceptionName)
{
  // Exception handle code
}
finally
{
  // this will execute every time
  // either we found exception or not
}

chevron_right


Example 1: Divide By Zero 

Kotlin

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main()
{
    try
      {
      // calling the function
      divide(10, 0
    }
    catch (ex : Exception)
    {
      // or you can also write your
      // own handle here
      println(ex.message) 
    }
}
  
// function which may give exception
fun divide(a : Int, b : Int)
{
    if (b == 0)
        throw Exception("Divide by zero"
    // even if you didn't write
    // this throw it will work fine.
    println("Division is :" + a / b)
}

chevron_right


Output:

Divide by zero

Example 2: Let’s try the same code with try-catch and finally.

Kotlin

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main()
{
    // first try block
    try 
    {
      // didn't throw any exception
      divide(20, 10
    }
    catch (ex : Exception)
    {
      // or you can also write your
      // own handle here
      println(ex.message) 
    }
    finally 
    {
      println("I'm executed")
    }
      
    // 2nd try block
    try 
    {
      // throw an exception
      divide(10, 0
    }
    catch (ex : Exception)
    {
      // or you can also write your
      // own handle here
      println(ex.message) 
    }
    finally 
    {
      println("I'm executed")
    }
}
  
fun divide(a : Int, b : Int)
{
    if (b == 0)
        throw Exception("Divide by zero"
    println("Division is :" + a / b)
}

chevron_right


Output:

Division is : 2
I'm executed
Divide by zero
I'm executed

Note that In the above example, finally is executed in both cases either exception occurs or not.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.