// 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.
Example 1:
Output:
Example 2:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer