w3resource

C# Program: Read and handle Int32 range exceptions in user input

C# Sharp Exception Handling: Exercise-7 with Solution

Write a C# program that reads a list of integers from the user. Handle the exception that occurs if the user enters a value outside the range of Int32.

Int32 is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 (which is represented by the Int32. MinValue constant) through positive 2,147,483,647 (which is represented by the Int32.

Sample Solution:

C# Sharp Code:

using System;
using System.Collections.Generic;

class Program {
  static void Main() {
    // Create a list to store integers
    List<int> numbers = new List<int>();

    try {
      // Prompt the user to input a list of integers, enter 'exit' to finish
      Console.WriteLine("Input a list of integers (Input 'exit' to finish):");

      // Continuously read user input until 'exit' is entered
      while (true) {
        Console.Write("Input an integer: ");
        string input = Console.ReadLine();

        // Check if user wants to exit the loop
        if (input.ToLower() == "exit")
          break;

        // Convert user input to an integer and add it to the list
        int number = ConvertToInt32(input);
        numbers.Add(number);
      }

      // Display the numbers entered by the user
      Console.WriteLine("Numbers entered:");
      foreach(int number in numbers) {
        Console.WriteLine(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 (OverflowException) {
      // Catch block for handling OverflowException when the entered value is outside the range of Int32
      Console.WriteLine("Error: The value entered is outside the range of Int32.");
    } 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 ConvertToInt32(string input) {
    return int.Parse(input); // Convert string to Int32
  }
}

Sample Output:

Input a list of integers (Input 'exit' to finish):
Input an integer: 645789
Input an integer: 23451
Input an integer: 123
Input an integer: 12
Input an integer: 1
Input an integer: exit
Numbers entered:
645789
23451
123
12
1
Input a list of integers (Input 'exit' to finish):
Input an integer: 21474836489
Error: The value entered is outside the range of Int32.
 
Input a list of integers (Input 'exit' to finish):
Input an integer: -2147483649
Error: The value entered is outside the range of Int32.

Explanation:

In the above exercise,

  • The Main method initializes a List<int> called numbers to store the integers entered by the user.

  • The program prompts the user to enter a list of integers. It continuously reads input from the user using a while loop.
  • Within the loop, the program checks if the user entered "exit" (case-insensitive). If so, it breaks out of the loop.
  • Otherwise, it calls the ConvertToInt32 method, passing the input as an argument, to convert the input string to an integer.
  • The ConvertToInt32 method uses int.Parse to convert the string to an integer. If the input cannot be parsed or if it is outside the range of Int32, a FormatException or an OverflowException is thrown, respectively.
  • 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. If an OverflowException occurs, it means the value entered by the user is outside the range of Int32, and the program handles it accordingly.
  • Any other exceptions that may occur are caught by the generic catch block, and a general error message is displayed.
  • Finally, the program displays the numbers entered by iterating over the numbers list and printing each element.

Flowchart:

Flowchart: C# Sharp Exercises - Read and handle Int32 range exceptions in user input.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Convert user input string to integer with exception handling.
Next: Divide two numbers with exception handling.

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.