我正在尝试一个 ApplicationException 异常,当输入不是数字时,它只会显示一条消息。这是我现在拥有的:
static void getBookInfo(Book book)
{
bool isNumeric;
float number;
string numberInput;
Console.Write("Enter Book Title: ");
book.Title = Console.ReadLine();
Console.Write("Enter Author's First Name: ");
book.AuthorFirstName = Console.ReadLine();
Console.Write("Enter Author's Last Name: ");
book.AuthorLastName = Console.ReadLine();
Console.Write("Enter Book Price: $");
numberInput = Console.ReadLine();
isNumeric = float.TryParse(numberInput, out number);
if (isNumeric)
book.Price = number;
else
{
throw new ApplicationException
(
"This is not a number!\n" +
"Please try again."
);
}
}
Whole Program.cs 编辑后有效。问题是 ApplicationException 部分显示了异常的整个打印输出,现在它只显示消息部分,而不是那样做。通常这很简单。 :)
using System;
namespace Lab_6
{
class Program
{
static void Main(string[] args)
{
Address address = new Address();
address.StreetNumber = "800";
address.StreetName = "East 96th Street";
address.City = "Indianapolis";
address.State = "IN";
address.ZipCode = "46240";
Book book = new Book();
try
{
getBookInfo(book);
book.PublisherAddress = address;
book.PublisherName = "Sams Publishing";
Console.WriteLine("----Book----");
book.display();
}
catch (NegativeInputException ex)
{
Console.WriteLine(ex.Message);
return;
}
catch (ApplicationException ex)
{
Console.WriteLine(ex.Message); // I had to change so I have only this,
// instead of whole printout.
return;
}
}
static void getBookInfo(Book book)
{
bool isNumeric;
float number;
string numberInput;
Console.Write("Enter Book Title: ");
book.Title = Console.ReadLine();
Console.Write("Enter Author's First Name: ")
book.AuthorFirstName = Console.ReadLine();
Console.Write("Enter Author's Last Name: ");
book.AuthorLastName = Console.ReadLine();
Console.Write("Enter Book Price: $");
numberInput = Console.ReadLine();
isNumeric = float.TryParse(numberInput, out number);
if (isNumeric)
book.Price = number;
else
{
throw new ApplicationException
(
"This is not a number!\n" +
"Please try again."
)
}
}
}
}
最佳答案
异常不显示任何内容。这取决于捕获它们的代码。
此外,您不应使用 ApplicationException
。要么使用 Exception
,要么使用更具体的东西,比如 FormatException
。
关于c# - 仅显示来自 ApplicationException 的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7642905/