CSharp - Write program to Handle Incorrect Number Input from User

Requirements

You will correctly handle non-numeric input from the user.

P:If the user entered something other than a number, deal with a runtime error.

Hint

Use insert a try-catch construct in an appropriate place.

Wrap the logic into the try block, which consists of the word try and a pair of curly brackets.

Then add a catch block with catch keyword and a pair of curly brackets after the try block.

Log the error as

Console.WriteLine("Incorrect input - cannot calculate"); 

Demo

using System;
class Program{/* ww  w  .  ja  v a 2 s .  c  o  m*/
    static void Main(string[] args){
        try{
            // Input of 1. number 
            Console.Write("Enter 1. number: ");
            string input1 = Console.ReadLine();
            int number1 = Convert.ToInt32(input1);

            // Input of 2. number 
            Console.Write("Enter 2. number: ");
            string input2 = Console.ReadLine();
            int number2 = Convert.ToInt32(input2);

            // Calculating 
            int result = number1 + number2;

            // Result output 
            Console.WriteLine("Sum of entered numbers is: " + result);
        }
        catch (Exception)
        {
            Console.WriteLine("Incorrect input - cannot calculate");
        }
    }
}

Result