handleInput function, different kind of user inputs can lead to exceptions that can break our program execution. Your task is to catch all possible exceptions and display appropriate messages to the user.- If the user input for a number is not a correct number, then
toIntthrowsNumberFormatException. In such case, you should print "Invalid input: ", and error message. - If the user input is a number, but the second number is zero, then
ArithmeticExceptionis thrown. In such case, you should print "Division by zero". - If the user input is an operator that is not supported by our calculator, then
IllegalOperatorExceptionis thrown. In such case, you should print "Illegal operator: ", and the operator that was entered by the user.
fun main() { while (true) { // Wrap below function call with try-catching block, // and handle possible exceptions. handleInput() } } fun handleInput() { print("Enter the first number: ") val num1 = readln().toInt() print("Enter an operator (+, -, *, /): ") val operator = readln() print("Enter the second number: ") val num2 = readln().toInt() val result = when (operator) { "+" -> num1 + num2 "-" -> num1 - num2 "*" -> num1 * num2 "/" -> num1 / num2 else -> throw IllegalOperatorException(operator) } println("Result: $result") } class IllegalOperatorException(val operator: String) : Exception("Unknown operator: $operator")
fun main() { while (true) { // Wrap below function call with try-catching block, // and handle possible exceptions. handleInput() } } fun handleInput() { print("Enter the first number: ") val num1 = readln().toInt() print("Enter an operator (+, -, *, /): ") val operator = readln() print("Enter the second number: ") val num2 = readln().toInt() val result = when (operator) { "+" -> num1 + num2 "-" -> num1 - num2 "*" -> num1 * num2 "/" -> num1 / num2 else -> throw IllegalOperatorException(operator) } println("Result: $result") } class IllegalOperatorException(val operator: String) : Exception("Unknown operator: $operator")