w3resource

C# Program: Negative number exception handling

C# Sharp Exception Handling: Exercise-2 with Solution

Write a C# program to implement a method that takes an integer as input and throws an exception if the number is negative. Handle the exception in the calling code.

Sample Solution:

C# Sharp Code:

using System;

class Program {
  static void Main() {
    try {
      // Prompt user to input an integer and read the input
      Console.Write("Input an integer: ");
      int number = Convert.ToInt32(Console.ReadLine());

      // Call the method to validate if the input is a positive number
      ValidatePositiveNumber(number);

      // Display the input as valid if it passes validation
      Console.WriteLine("Valid input: " + number);
    } catch (NegativeNumberException ex) {
      // Catch block for handling NegativeNumberException
      Console.WriteLine("Error: " + ex.Message);
    } catch (FormatException) {
      // Catch block for handling FormatException (non-integer input)
      Console.WriteLine("Error: Invalid input. Please enter an integer.");
    } catch (Exception ex) {
      // Catch block for handling other types of exceptions
      Console.WriteLine("An error occurred: " + ex.Message);
    }
  }

  // Method to validate if the number is positive
  static void ValidatePositiveNumber(int number) {
    if (number < 0) {
      // Throw NegativeNumberException if the number is negative
      throw new NegativeNumberException("Negative number not allowed.");
    }
  }
}

// Custom exception class for handling negative number scenarios
class NegativeNumberException: Exception {
  public NegativeNumberException(string message): base(message) {}
}

Sample Output:

Input an integer: 12
Valid input: 12
 
Input an integer: a
Error: Invalid input. Please enter an integer.
 
Input an integer: -34
Error: Negative number not allowed.

Explanation:

In the above exercise,

  • The "ValidatePositiveNumber()" method is called with the number as an argument. This method checks if the number is less than zero. If it is, it throws a custom exception called NegativeNumberException with the message "Negative number is not allowed."
  • In the Main method, exceptions are handled using catch blocks. If a NegativeNumberException is thrown by the ValidatePositiveNumber method, it is caught and an error message is displayed.
  • If a FormatException occurs, the user entered a non-integer value. This exception is caught and an appropriate error message is displayed.
  • Any other exceptions are caught by the generic catch block, and a general error message is displayed

Flowchart:

Flowchart: C# Sharp Exercises - Negative number exception handling.

Flowchart: C# Sharp Exercises - Negative number exception handling.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: User input division with exception handling.
Next: File opening 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.