我应该编写一个程序,让用户输入一本书的名称、描述和页数,如果名称或描述为空,或者页数小于零,程序应该捕获异常. 老师说我们需要在类的“set”函数中捕捉异常,但我似乎无法正确理解。这是类的样子:
class Book
{
private string Name;
private string Description;
private int Pages;
public string GetName()
{
return Name;
}
public string GetDescription()
{
return Description;
}
public int GetPages()
{
return Pages;
}
public void SetName(string Name)
{
if (this.Name == null)
throw new Exception("The name can't be blank");
else
this.Name = Name;
}
public void SetDescription(string Description)
{
if (this.Description == null)
throw new Exception("The description can't be blank");
else
this.Description = Description;
}
public void SetPages(int Pages)
{
if(Pages > 0)
{
this.Pages = Pages;
}
else
{
Console.WriteLine("Number of pages has to be higher than zero");
}
}
public void Write()
{
Console.WriteLine("Name: {0}, Description: {1}, Pages: {2}", Name, Description, Pages);
}
}
主要看起来像这样:
Book hp = new Book();
hp.SetName("Harry Potter");
hp.SetDescription("It's okay");
hp.SetPages(-500);
hp.Write();
我知道 SetPages 并没有真正使用 catch 方法,但我认为它仍然有效(尽管如果有人知道如何使用 catch 方法,我会很高兴听到)。我的问题是,即使名称和描述字符串明显有输入,仍然会抛出空异常。有人知道我该如何解决吗?任何帮助,将不胜感激。
catspeake
MMMHUHU
相关分类