kotlin
  1. kotlin-throw-keyword

Kotlin Throw Keyword

In Kotlin, the throw keyword is used to throw an exception. It allows you to manually throw an exception when a specific condition is met in your code. In this tutorial, we'll discuss how to use the throw keyword in Kotlin.

Syntax

The syntax for using the throw keyword in Kotlin is as follows:

throw Exception("Error message")

You can replace "Exception" with any type of exception class and "Error message" with your custom error message.

Example

Let's say we want to throw an exception when a user tries to divide a number by zero. We can write the following code:

fun divide(a: Int, b: Int): Int {
   if (b == 0) throw ArithmeticException("Division by zero")
   return a / b
}

fun main() {
   println(divide(10, 2))
   println(divide(10, 0))
}

In this example, we define a function called divide that takes two integers as input. If the second integer is zero, we throw an ArithmeticException with a custom error message "Division by zero". In the main function, we call the divide function twice with different input values and observe the output.

Output

When we run the above code, the output will be:

5
Exception in thread "main" java.lang.ArithmeticException: Division by zero
   at DivideExample.divide(DivideExample.kt:2)
   at DivideExample.main(DivideExample.kt:8)

The first line of output shows the output of divide(10, 2) which is 5. The second line of output shows the exception thrown by the divide function when we try to divide 10 by 0.

Explanation

The throw keyword is used to explicitly throw an exception in Kotlin. When a throw statement is encountered, the program stops executing the current block of code and looks for the nearest catch block that can handle the thrown exception.

In the example above, we throw an ArithmeticException when the second input value to the divide function is 0. This exception is propagated up the call stack until it reaches the main function where it is caught and printed to the console.

Use

The throw keyword is useful when you need to handle exceptional conditions in your code. You can use it to throw an exception when an error occurs in your program, or when you need to enforce certain conditions.

Important Points

  • Always provide a custom error message when throwing an exception using the throw keyword.
  • Be careful not to throw too many exceptions or throw exceptions unnecessarily.
  • Remember to catch and handle exceptions appropriately using try-catch blocks.

Summary

In this tutorial, we learned about the throw keyword in Kotlin. We covered the syntax, example, output, explanation, use, and important points of using the throw keyword in Kotlin. With this knowledge, you can now use the throw keyword to handle exceptional conditions in your Kotlin code.

Published on: