【问题标题】:Determine what threw an exception?确定是什么引发了异常?
【发布时间】:2017-05-22 09:44:39
【问题描述】:

我有一个带有各种小程序的 wpf 应用程序,其中一个可以计算平行四边形的面积。我正在添加一些错误处理,以便如果用户在高度或宽度框中输入的值大于double.MaxValue,则会显示错误消息。如何确定哪个文本框输入触发了异常,以便我可以将其与错误消息一起返回?如果重要的话,高度和宽度框在用户控件中。

private void AreaOfParallelogramCalcBtn_Click(object sender, RoutedEventArgs e)
{
    if (Convert.ToDouble(AreaOfParallelogramHeightTxtBox.Text) > double.MaxValue == false || (Convert.ToDouble(AreaOfParallelogramWidthTxtBox.Text) > double.MaxValue == false))
    {
        MessageBox.Show("Seriously?  That is a pretty big number.  Please try again.");
    }
    else
    {
        AreaOfParallelogramResultTxtBox.Text =
        CalculateAreaOfParallelogram.Calculate(Convert.ToDouble(AreaOfParallelogramHeightTxtBox.Text),
        Convert.ToDouble(AreaOfParallelogramWidthTxtBox.Text)).ToString();
    }
}

【问题讨论】:

  • 单独检查和显示每个 TextBox 的消息而不是 ORing 两个检查有什么问题?
  • @EugenePodskal 什么都没有,我不敢相信我完全忽略了这一点。谢谢你。我对这一切都很陌生。
  • 附注,但ToDouble(...) > double.MaxValue 永远不会是true。
  • @HenkHolterman 我注意到了,我该如何解决这个问题?

标签: c# wpf error-handling


【解决方案1】:

使用异常源

   try
    {
    ....
    }
    Catch(Exception ex)
    {
     MessageBox.Show(ex.Source)
    }

【讨论】:

    【解决方案2】:

    所以这可能不是最好的方法,但这是我最终做的并取得了预期的结果。

        private void AreaOfParallelogramCalcBtn_Click(object sender, RoutedEventArgs e)
        {
            if (Convert.ToDouble(AreaOfParallelogramHeightTxtBox.Text) > 25000000)
            {
                MessageBox.Show($"Height input out of range.  Height must be less than 25,000,000\n{Convert.ToDouble(AreaOfParallelogramHeightTxtBox.Text):n0} is a pretty big number.  Please try again.", "*WARNING*", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            else if (Convert.ToDouble(AreaOfParallelogramWidthTxtBox.Text) > 25000000)
            {
                MessageBox.Show($"Width input out of range.  Width must be less than 25,000,000\n{Convert.ToDouble(AreaOfParallelogramWidthTxtBox.Text):n0} is a pretty big number.  Please try again.", "*WARNING*", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            else
            {
                AreaOfParallelogramResultTxtBox.Text =
                CalculateAreaOfParallelogram.Calculate(Convert.ToDouble(AreaOfParallelogramHeightTxtBox.Text),
                Convert.ToDouble(AreaOfParallelogramWidthTxtBox.Text)).ToString(CultureInfo.InvariantCulture);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2019-07-06
      • 2015-12-06
      • 2018-08-14
      • 2010-11-06
      • 2010-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 2017-05-16
      相关资源
      最近更新 更多