w3resource

C# Program: Convert user input string to integer with exception handling

C# Sharp Exception Handling: Exercise-6 with Solution

Write a C# program that reads a string from the user and converts it to an integer. Handle the exception if the input cannot be parsed into an integer.

Sample Solution:

C# Sharp Code:

using System;

class Program {
  static void Main() {
    try {
      // Prompt the user to input a number
      Console.Write("Input a number: ");
      string input = Console.ReadLine();

      // Attempt to convert the user input to an integer
      int number = ConvertToInt(input);

      // Display the converted number
      Console.WriteLine("Number: " + number);
    } catch (FormatException) {
      // Catch block for handling FormatException when non-integer input is entered
      Console.WriteLine("Error: Invalid input. Please enter a valid integer.");
    } catch (Exception ex) {
      // Catch block for handling other types of exceptions
      Console.WriteLine("An error occurred: " + ex.Message);
    }
  }

  // Method to convert string input to an integer
  static int ConvertToInt(string input) {
    return int.Parse(input); // Convert string to integer
  }
}

Sample Output:

Input a number: abc
Error: Invalid input. Please enter a valid integer.
 
Input a number: 123
Number: 123

Explanation:

In the above exercise,

  • The "Main()" method prompts the user to input a number as a string using Console.Write() and Console.ReadLine(). The input is stored in the input variable.
  • The program calls the ConvertToInt method, passing the input string as an argument.
  • The ConvertToInt method uses int.Parse to convert the string to an integer. If the input cannot be parsed, a FormatException is thrown.
  • In the "Main()" method, the exceptions are handled using catch blocks. If a FormatException occurs, it means the input was not a valid integer. The program catches this exception and displays an appropriate error message.
  • Any other exceptions are caught by the generic catch block, and a general error message is displayed.

Flowchart:

Flowchart: C# Sharp Exercises - Convert user input string to integer with exception handling.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Calculate the average of integers in an array.
Next: Read and handle Int32 range exceptions in user input.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.