【发布时间】:2017-10-04 11:12:59
【问题描述】:
如果 GPA 输入为 int 而不是 double,我必须抛出 FormatException,但我做不到。但是,当在 studentID 字段中输入十进制值时,我能够抛出 FormatException。我所知道的是默认情况下,双数据类型接受 int 值,这就是它不抛出异常的原因,但我需要确保作为 GPA 输入的值是双精度值。
using System;
using static System.Console;
// Declare a Student
// ID must be an integer and gpa must be a double to continue
namespace Debug4_4
{
class Debug4_4
{
static void Main()
{
Student stu = new Student();
bool areNumbersGood = false;
while (!areNumbersGood)
{
try
{
stu.setID();
stu.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("Valid student");
}
}
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);
}
catch (FormatException fe)
{
throw (fe);
}
}
//throw (fe);
//}
public void setGPA()
{
string stuGPAString;
//string stuGPAString;
try
{
Write("Enter student GPA ");
stuGPAString = ReadLine();
stuGpa = Convert.ToDouble(stuGPAString);
}
catch (FormatException fe)
{
throw (fe);
}
}
}
}
【问题讨论】:
-
学生不能有 4 GPA 或 5 GPA 吗?如果用户输入的 int 值可以转换为 double 为什么要进行这种验证?
-
stuGpaIS 是双重的。究竟是什么问题?您已经声明您认识到int可以转换为double,并且您将输入存储在double字段中。所以你已经确保输入是double。 -
闻起来像家庭作业。与其捕获异常来检测错误,不如尝试 Integer.TryParse 并在失败时抛出您自己的异常。
-
另外,如果你的
catch的唯一目的是throw确切的例外,那么你真的根本不需要try/catch块。他们什么也没做。
标签: c# exception-handling formatexception