简体   繁体   English

Try 和 catch 块未捕获格式异常

[英]Try and catch block is not catching format exception

I am trying to catch format exception but the program stops on try block and never reaches to catch block, what is the problem with the code please help me?我正在尝试捕获格式异常,但程序在 try 块上停止并且永远不会到达 catch 块,代码有什么问题请帮助我?

private void txtBags_TextChanged(object sender, EventArgs e) 
{
   if (txtBags.Text != "" && PackingBox.Text != "") 
   {
      try 
      {
         txtQty.Text = ((Convert.ToDecimal(txtBags.Text)) * 
         (Convert.ToDecimal(PackingBox.Text)) / 100).ToString();
      } 
      catch (FormatException eX) 
      {
         MessageBox.Show(eX.Message);
      }
   } 
   else 
   {
      txtQty.Text = "";
   }
}

I want to catch the exception and show the message to the user?我想捕获异常并向用户显示消息? please tell me how can I do that?请告诉我我该怎么做?

Why handle the exception at all?为什么要处理异常? Why not just avoid it altogether by using TryParse ?:为什么不通过使用TryParse完全避免它?:

if (!string.IsNullOrEmpy(txtBags.Text) && !string.IsNullOrEmpty(PackingBox.Text))
{
    if (!Decimal.TryParse(txtBags.Text, out var bags))
    {
        // handle parse failure
        return;
    }

    if (!Decimal.TryParse(PackingBox.Text, out var packingBox))
    {
        // handle parse failure
        return;
    }

    txtQty.Text = (bags * packingBox / 100).ToString();
}

If you're not building with Roslyn/are using an older version of C#, you might need to define the variable beforehand:如果您不使用 Roslyn 构建/使用旧版本的 C#,则可能需要事先定义变量:

decimal bags;
if (!Decimal.TryParse(txtBags.Text, out bags))

And then the same with PackingBox, of course.当然,PackingBox 也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM