Exercise: Handling Exceptions
Elevate your Kotlin skills by implementing exception handling and ensuring robust error management.
We'll cover the following
Problem statement
In the below handleInput
function, different kinds of user inputs can lead to exceptions that might 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
throwsNumberFormatException
. In such a case, you should print “Invalid input:” and an error message.If the user input is a number, but the second number is zero, then
ArithmeticException
is thrown. In such a case, you should print a “Division by zero” message.If the user input is an operator that is not supported by the calculator, then
IllegalOperatorException
is thrown. In such a case, you should print “Illegal operator:” and the operator that was entered by the user.
Instructions
In the provided code, the handleInput
function manages user input. Your task is to implement exception handling within the handleInput
function to address the specified cases. Additionally, wrap the function call with a try
-catch
block in the main
function to ensure proper handling of any potential exceptions.
The actual output when running the provided code should be as follows:
Get hands-on with 1400+ tech skills courses.