需要用于控制默认Exception.ToString()的解决方案 [英] Need solution for controlling default Exception.ToString()

查看:123
本文介绍了需要用于控制默认Exception.ToString()的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:


namespace ConsoleApplication6
{
  using System;

  class Program
  {
    static void Main(string[] args)
    {
      var ex = new Exception("Outer", new MyException("Inner"));
      Console.WriteLine(ex.ToString());
      Console.ReadKey();
    }
  }

  public class MyException : Exception
  {
    public MyException(string message)
      : base(message) 
    {}

    public override string ToString() 
    { 
      return "Nothing here to see"; 
    }
  }
}

推荐答案

您好Werner,

Hi Werner,

如我所见,您有两个选择:

As I see it you have two options:

  1. 仅抛出并捕获 MyException 并使用其ToString().
  2. 为Exception类创建扩展,该扩展检查内部异常以及其类型是否为 MyException 它会根据需要简单地获取ToString或消息.然后,当它被捕获时,调用扩展而不是ToString.
  1. Only throw and catch the MyException and use its ToString().
  2. Create an extension for the Exception class which checks the inner exception and if its type is the MyException it simpy gets its ToString or message as needed. Then when it is caught call the extension instead of ToString.

HTH


这篇关于需要用于控制默认Exception.ToString()的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆