You need to enable JavaScript to run this app. WinForms中如何同时结合if条件与Try-Catch-Finally使用自定义异常
优惠活动
大模型
产品
解决方案
定价
更多

WinForms中如何同时结合if条件与Try-Catch-Finally使用自定义异常

自定义异常失效的核心原因
  • 未主动抛出异常:自定义异常类仅完成定义无法自动触发,必须在规则校验不通过的分支,通过throw语句显式抛出异常实例,才会被外层的try-catch结构捕获。当前代码在正则不匹配的分支没有任何抛出异常的逻辑,自然无法触发自定义异常。
  • 代码逻辑顺序颠倒:将无异常可能的文本框赋值操作放进try块,而把校验逻辑放在try块外部,导致catch块没有任何可捕获的目标。
  • 异常可访问性不足:三个自定义异常是ProductClass的私有嵌套类,WinForm UI层无法引用对应类型,无法精准捕获分类异常。
  • 错误信息读取错误:catch块中读取了异常的InnerException属性,而自定义抛出的异常没有配置内部异常,该值永远为null,就算捕获到异常也会输出无意义的空内容。
  • 正则规则存在漏洞:库存校验的正则@"^[0-9]"缺少结束锚点$,只要字符串开头是数字,后续带非法字符也会通过校验,存在判断偏差。
正确实现步骤

1. 调整自定义异常的可访问性

将自定义异常类从ProductClass的私有嵌套结构中移出,设置为公共可访问,确保UI层可以正常引用、精准捕获:

// 独立定义为公共类,方便全局引用
public class ProductNameFormatException : Exception
{
    public ProductNameFormatException(string message) : base(message) { }
}
public class QuantityFormatException : Exception
{
    public QuantityFormatException(string message) : base(message) { }
}
public class PriceFormatException : Exception
{
    public PriceFormatException(string message) : base(message) { }
}

2. 重构校验方法,绑定校验规则与异常抛出

将每个校验方法的逻辑调整为:先执行正则校验,不满足规则时立刻抛出对应类型的自定义异常,满足规则时返回转换后的合法值:

public string Product_Name(string name)
{
    // 补全正则锚点,确保全字符串匹配英文字母
    if (!Regex.IsMatch(name, @"^[a-zA-Z]+$"))
    {
        // 校验不通过,主动抛出自定义异常
        throw new ProductNameFormatException("产品名称仅支持英文字符,不能包含数字、符号或特殊内容");
    }
    return name;
}

public int Quantity(string qty)
{
    // 修正正则,匹配全数字内容,补全结束锚点
    if (!Regex.IsMatch(qty, @"^[0-9]+$"))
    {
        throw new QuantityFormatException("库存数量仅支持正整数,不能包含其他非法字符");
    }
    return Convert.ToInt32(qty);
}

public double SellingPrice(string price)
{
    if (!Regex.IsMatch(price, @"^(\d*\.)?\d+$"))
    {
        throw new PriceFormatException("商品售价格式错误,仅支持带小数点的合法金额");
    }
    return Convert.ToDouble(price);
}

3. 在UI层正确使用Try-Catch-Finally结构

将所有校验、赋值、保存的流程全部放到try块内部,在校验不通过抛出异常时,由catch块精准捕获对应类型的异常,输出提示信息;finally块放置无论成功或失败都需要执行的通用逻辑:

private void btnSaveProduct_Click(object sender, EventArgs e)
{
    try
    {
        // 所有可能抛出异常的校验、转换、实例化操作全部放在try块内
        string validName = Product_Name(txtProductName.Text.Trim());
        int validQty = Quantity(txtQuantity.Text.Trim());
        double validPrice = SellingPrice(txtSellingPrice.Text.Trim());

        // 所有校验通过后,再实例化ProductClass完成业务逻辑
        ProductClass product = new ProductClass(
            ProductName: validName,
            Category: txtCategory.Text.Trim(),
            MfgDate: txtMfgDate.Text.Trim(),
            ExpDate: txtExpDate.Text.Trim(),
            Price: validPrice,
            Quantity: validQty,
            Description: txtDesc.Text.Trim()
        );

        MessageBox.Show("产品信息保存成功");
    }
    catch (ProductNameFormatException ex)
    {
        // 捕获产品名称校验错误,弹窗+控制台输出提示
        MessageBox.Show(ex.Message, "产品名称校验失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
        Console.WriteLine($"[校验错误] {ex.Message}");
    }
    catch (QuantityFormatException ex)
    {
        MessageBox.Show(ex.Message, "库存数量校验失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
        Console.WriteLine($"[校验错误] {ex.Message}");
    }
    catch (PriceFormatException ex)
    {
        MessageBox.Show(ex.Message, "商品售价校验失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
        Console.WriteLine($"[校验错误] {ex.Message}");
    }
    catch (Exception ex)
    {
        // 兜底捕获其他未预期的系统异常
        MessageBox.Show($"系统处理失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        Console.WriteLine($"[系统异常] {ex}");
    }
    finally
    {
        // 无论流程成功或异常中断,都会执行的通用逻辑
        Console.WriteLine("产品信息校验流程执行完毕");
    }
}
实现效果说明

按照上述结构调整后,只要任意输入项不符合正则规则,对应的自定义异常就会被主动抛出,被UI层的catch块捕获,同时通过MessageBox和控制台输出明确的错误提示,finally块的逻辑不受异常中断影响正常执行。

内容的提问来源于stack exchange,提问作者Ciel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.13 00:15:06