BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Kotlin throw keyword with example

Last Updated: March 7, 2019 by Chaitanya Singh | Filed Under: Kotlin Tutorial

In this short guide, we will learn how to throw a exception using throw keyword in Kotlin.

Kotlin throw keyword example

In the following example we are throwing an exception using throw keyword. Here I have thrown parent Exception class, you can throw any exception such as ArithmeticException, ArrayIndexOutOfBoundsException etc.

fun main(args: Array<String>) {
    print("Enter your name: ")
    val name = readLine()

    try{
        if (name == "Chaitanya"){
            throw Exception("You don't have access")
        }
        else
        {
            println("Welcome! You have access")
        }
    }
    catch (e: Exception){
        println(e.message)
    }
}

Output:
Kotlin throw keyword example

❮ PreviousNext ❯

Top Related Articles:

  1. Kotlin Try Catch with example
  2. Kotlin Nested and Inner Class with examples
  3. Kotlin Keywords, Soft Keywords and Identifiers
  4. Kotlin Higher order function with example
  5. Kotlin Class and Objects – Object Oriented Programming (OOP)

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Kotlin Tutorial

  • Kotlin Tutorial
  • Kotlin in Eclipse IDE
  • Kotlin in IntelliJ
  • First Kotlin Program
  • Kotlin Keywords
  • Kotlin Variables
  • Kotlin Type Casting
  • Kotlin operators
  • Kotlin Input/Output
  • Kotlin Comments

Kotlin String

  • Kotlin String

Kotlin Array

  • Kotlin Array
  • Kotlin Range

Control Flow

  • Kotlin if expression
  • Kotlin when expression
  • Kotlin for loop
  • Kotlin while loop
  • Kotlin do-while loop
  • Kotlin continue
  • Kotlin break

Kotlin Function

  • Kotlin Function
  • Kotlin Recursion
  • Kotlin default and named arguments
  • Lambda functions
  • Higher Order Function

Exception Handling

  • Exception Handling
  • Kotlin try catch
  • Multiple catch blocks
  • Nested try catch
  • Throw keyword
  • Kotlin try expression

Kotlin OOP

  • Class and Objects
  • Kotlin Constructors
  • Kotlin Inheritance
  • Visibility Modifiers
  • Kotlin abstract class
  • Kotlin Interfaces
  • Nested and Inner Class
  • Kotlin Data Class
  • Kotlin Sealed Class

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap