如何将自定义异常放入Try Catch Finally中,但同时在winforms中使用If条件



我做了三个自定义异常。产品名称、数量和价格,但当我试图将其包含在试用中时,它不会出现。我只需要处理异常,然后将其显示在控制台或消息框中。

这就是它最初的样子:

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) { }
}

}

您需要编写:

catch (StringFormattException ex)
{
string msg = ex.Message;
if ( ex.InnerException != null )
msg += $" ({ex.InnerException.Message})";
// Also you can do a loop to get all inners
Console.WriteLine("String format error: " + msg);
}

因为如果你写:

catch (Exception StringFormattException)
{
...
}

这里Exception是一个类型,StringFormattException是异常上下文实例的变量名,如:

string StringFormattException = "test";

try-catch(C#参考(

相关内容

  • 没有找到相关文章

最新更新