ADVERTISEMENT
ADVERTISEMENT

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("Hello!")
}

// 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.")
	else
		println("The string lenght is >=8.")
}

Output:

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()

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

Output:

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.