【问题标题】:C# Determinig if exception initialized with a messageC#确定是否使用消息初始化异常
【发布时间】:2015-12-14 22:47:53
【问题描述】:

有没有办法在捕获异常时确定它是否是用非默认消息构造的。

        try
        {
            throw new Exception(message);      // case 1
            //throw new Exception();           // case 2
        }

        catch(Exception exp)
        {
            /* what do I put here such that if the case 2 exception were
               caught it would output exp.ToString() instead of exp.Message? */

            textBox1.Text = exp.Message;  // case 1 handeling

        }

只是为了澄清什么时候抛出异常(消息),我希望它输出 exp.Message,而当抛出异常()时,我想输出 exp.ToString()。我宁愿在不添加自定义异常的情况下完成此操作。谢谢。

【问题讨论】:

  • 在上面的示例中,如果 throw Exception(),则 exp.Message 的值显示为“抛出了 'System.Exception' 类型的异常。”

标签: c# exception constructor try-catch throw


【解决方案1】:

您需要根据默认异常检查消息

catch (Exception e)
{
  bool isDefaultMessage = e.Message == new Exception().Message;
}

更新

异常的不同类型

catch (Exception e)
{
  bool isDefaultMessage = false;
  try
  {
     var x = (Exception) Activator.CreateInstance(e.GetType());
     isDefaultMessage = e.Message == x.Message;
  }
  catch (Exception) {} // cannot create default exception.
}

【讨论】:

  • 看起来像textBox1.Text = isDefaultMessage ? e.ToString() : e.Message;。我喜欢这种方法。
  • 当 catch() 块收到不同类型的异常时会发生什么情况,默认消息如 IndexOutOfRange 或 FileNotFound。
  • 用不同类型的异常更新了答案。
  • 当我键入 x.Message 时,编译器会报错,'object' 不包含'Message' 的定义,并且找不到接受'object' 类型的第一个参数的扩展方法“Message”(您是否缺少 using 指令或程序集引用?)。
  • 糟糕,需要强制转换为异常;查看新代码。
猜你喜欢
  • 1970-01-01
  • 2013-03-25
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多