Handling negative integers gracefully

Report a typo

Write a program that prompts the user to enter a non-negative integer. If the user enters a negative integer, the program should catch the exception and print an error message. Otherwise, the program should print the square of the input integer.

Sample Input 1:

5

Sample Output 1:

25

Sample Input 2:

-3

Sample Output 2:

Invalid input! Please enter a non-negative integer.
Write a program in Kotlin
import kotlin.NumberFormatException

fun main() {
// Read user input as a string
val input = readLine()

try {
// TODO: Convert the input string to an integer
// TODO: Check if the integer is non-negative
// TODO: If the integer is non-negative, print its square
// TODO: If the integer is negative, throw an exception with an error message
} catch (e: NumberFormatException) {
// TODO: Handle the exception if the input is not a valid integer
}
}

Create a free account to access the full topic