【发布时间】:2020-12-13 05:15:14
【问题描述】:
我做了三个自定义例外。对于产品名称、数量和价格,但是当我尝试将其包含在尝试中时,它不会显示出来。我只需要异常工作,然后让它显示在控制台或消息框中。
原来是这样的:
public string Product_Name(string name) {
if (!Regex.IsMatch(name, @"^[a-zA-Z]+$"))
//Exception here
return name;
}
public int Quantity(string qty) {
if (!Regex.IsMatch(qty, @"^[0-9]"))
//Exception here
return Convert.ToInt32(qty);
}
public double SellingPrice(string price)
{
if (!Regex.IsMatch(price.ToString(), @"^(\d*\.)?\d+$"))
//Exception here
return Convert.ToDouble(price);
}
这是我尝试过的:
public string Product_Name (string name)
{
if (!Regex.IsMatch(name, @"^[a-zA-Z]+$"))
try
{
name = txtProductName.Text;
}
catch (Exception StringFormattException)
{
Console.WriteLine("Error info:" + StringFormattException.InnerException);
}
finally
{
Console.WriteLine("Executed.");
}
return name;
}
另外两个也一样。
这是我放置自定义异常的类:
class ProductClass
{
private int _Quantity;
private double _SellingPrice;
private string _ProductName, _Category, _ManufacturingDate, _ExpirationDate, _Description;
public ProductClass(string ProductName, string Category, string MfgDate, string ExpDate, double Price, int Quantity, string Description)
{
this._Quantity = Quantity;
this._SellingPrice = Price;
this._ProductName = ProductName;
this._Category = Category;
this._ManufacturingDate = MfgDate;
this._ExpirationDate = ExpDate;
this._Description = Description;
}
public string productName
{
get
{
return this._ProductName;
}
set
{
this._ProductName = value;
}
}
public string Category
{
get
{
return this._Category;
}
set
{
this._Category = value;
}
}
public string manufacturingDate
{
get
{
return this._ManufacturingDate;
}
set
{
this._ManufacturingDate = value;
}
}
public string expirationDate
{
get
{
return this._ExpirationDate;
}
set
{
this._ExpirationDate = value;
}
}
public string description
{
get
{
return this._Description;
}
set
{
this._Description = value;
}
}
public int quantity
{
get
{
return this._Quantity;
}
set
{
this._Quantity = value;
}
}
public double sellingPrice
{
get
{
return this._SellingPrice;
}
set
{
this._SellingPrice = value;
}
}
class NumberFormattException : Exception
{
public NumberFormattException(string Quantity) : base(Quantity) { }
}
class StringFormattException : Exception
{
public StringFormattException(string Product_Name) : base(Product_Name) { }
}
class CurrencyFormatException : Exception
{
public CurrencyFormatException( string SellingPrice) : base(SellingPrice) { }
}
}
【问题讨论】:
-
阅读异常情况。单个
try可以有多个关联的catch块,每个块都有不同的异常类型。例如,如果您有 3 种可能抛出的异常类型(Ex1、Ex2和Ex3),您可以编写try { SomeCode(); } catch (Ex1 e1) { CatchCode1(e1); } catch (Ex2 e2) { CatchCode2(e2); } catch (Ex3 e3) { CatchCode(e3); } finally { FinCode(); }。注意catch语句的格式,异常规范就像一个方法参数规范:catch(ExceptionType exVariable)。如果你有多个 catch 块,第一个匹配的获胜
标签: c# winforms exception try-catch-finally