'c# Try-catch with conditional statement?

I'm trying to validate that the input for gpa entered is between 0.00 and 4.00 If this condition isn't met, the program has to stay within the while loop until both conditions are acceptable(student ID and GPA).

I tried an if-else statement within the setGPA() (Student.cs), which didn't work. I was trying to have a nested try-catch, but if the inner catch is initiated, that satisfies the outer try and breaks out of the loop.

Here's my code:

namespace start_p3s3_Debugging
{
class Program
{
   static void Main()
    {
        Student student1 = new Student();
        bool areNumbersGood = false;

        while (!areNumbersGood)
        {
            try
            {
                student1.setID();
                student1.setGPA();
                areNumbersGood = true;
        
            }
            catch (FormatException e)
            {
                WriteLine(e.Message);
                WriteLine("(Either the student ID or the GPA");
                WriteLine(" was not in the correct format.)");
                WriteLine("You will have to re-enter the student data.");
            }
        }
        WriteLine("You entered a valid student.");
    }
}

}

and the <Student.cs>

   using System;
   using static System.Console;

  namespace start_p3s3_Debugging
  {
   public class Student
   {
    private int stuId;
    private double stuGPA;

    public void setID()
    {
        string stuNumber;

        try
        {
            Write("Enter student ID: ");
            stuNumber = ReadLine();
            stuId = Convert.ToInt32(stuNumber);
            WriteLine(stuNumber);
        }
        catch (FormatException fe)
        { 
            throw (fe);
        }
    }

    public void setGPA()
    {
        string stuGPAString;

        try
        {
            Write("Enter student GPA: ");
            stuGPAString = ReadLine();
            stuGPA = Convert.ToDouble(stuGPAString);
        }
        catch (FormatException fe)
        {
            throw (fe);
        }
       
    }

}

}

Any help is appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source