article banner

Exercise: Catching exceptions

In the below 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 toInt throws NumberFormatException. 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 ArithmeticException is 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 IllegalOperatorException is thrown. In such case, you should print "Illegal operator: ", and the operator that was entered by the user.

Starting code:

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

This problem can either be solved in the below playground or you can clone kotlin-exercises project and solve it locally. In the project, you can find code template for this exercise in essentials/exceptions/HandleExceptions.kt. You can find there starting code.

Once you are done with the exercise, you can check your solution here.

Playground

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