Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin
communitycreator

What are exceptions in Kotlin?

Shubham Singh Kshatriya

Overview

An exception is an unexpected error that occurs at run time and leads to the termination of the program execution.

There are two types of exceptions in general.

  1. Checked exceptions: Exceptions that occur at compile time.
  2. Unchecked exceptions: Exceptions that occur at run time.

We only have unchecked exceptions in Kotlin. All exception classes inherit the Throwable class.

Example 1

Let's see an example of an ArithmeticException in Kotlin in the following code snippet.

fun main() {
    
    // dividing by zero will throw an arithmetic exception
    var n = 1/0
    println("n = $n")
}
Example of ArithmeticException in Kotlin

Explanation

In the code snippet above:

  • Line 2: We deliberately create an ArithmeticException by dividing a number by zero. Upon execution of the program, the exception is thrown and the program gets terminated.

    Exception handling in Kotlin

    Exception handling is a mechanism by which we can handle unchecked exceptions and stop the termination of program execution due to them.

    An exception can be handled using the try-catch block. All the executable code is written inside the try block. In case an exception occurs, the try block will throw that exception. The exception thrown by try block is captured by the catch block, where the exception is actually handled.

    Note: A try block should be immediately followed by a catch block.

    Syntax

    try {
        // code that can throw a exception
    } catch (e: Exception) {
        // handle the exception
    }
    Syntax of try-catch

    Example 2

    Let's see an example of ArithmeticException handling in Kotlin using try-catch, in the following code snippet.

    fun main() {
        try {
          // dividing by zero will throw an arithmetic exception
          var n = 1/0
          println("n = $n")
        } catch (e: ArithmeticException) {
          println("Cannot perform 'Divide by Zero'")
        }
    }
    Example of ArithmeticException using try-catch

    Explanation

    In the code snippet above:

    • Lines 2-6: We shift our code inside a try block.
    • Line 4: The ArithmeticException is thrown by try block and handled in the catch block. Cannot perform 'Divide by Zero' is printed on the console. Here, the program execution does not get terminated.
    • Lines 6-8: We use a catch block to handle the ArithmeticException.

      RELATED TAGS

      kotlin
      communitycreator

      CONTRIBUTOR

      Shubham Singh Kshatriya
      RELATED COURSES

      View all Courses

      Keep Exploring