Kotlin program of using throw keyword

Kotlin example to demonstrate the use throw keyword.
Submitted by IncludeHelp, on April 11, 2022

The throw keyword

The "throw" keyword is used to throw an explicit exception or a custom exception.

Example 1:

// Main Function
fun main(args: Array<String>) {	
	ThrowDemo("Hello, world!")

// ThrowDemo() function to check 
// whether string's lenght is 
// equal to or greater than 8
fun ThrowDemo(str: String) {
	// Comparing the lenght of the string
	if (str.length < 8)
		throw ArithmeticException("The string is too short.")
		println("The string lenght is >=8.")


The string lenght is >=8.
Exception in thread "main" java.lang.ArithmeticException: The string is too short.
 at FileKt.ThrowDemo (File.kt:13) 
 at FileKt.main (File.kt:4) 
 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2) 

Example 2:

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

        if (user_name == "alex"){
            throw Exception("$user_name don't have an access!")
            println("Welcome! $user_name. You're In.")
    catch (exp: Exception){
        println("Exception: " + exp.message)


Run 1:
Enter the user name: alex
Exception: alex don't have an access!

Run 2:
Enter the user name: shivang
Welcome! shivang. You're In.

Kotlin Exception Handling Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.