代码之家  ›  专栏  ›  技术社区  ›  user3163495

C#Exception-将“源错误”设为调用方法的行

  •  2
  • user3163495  · 技术社区  · 7 年前

    在C#中,如果调用一个固定方法(如Regex.Replace)并引发异常,则错误消息会标记调用该方法的行,如下所示:

    //
    //
    string str = Regex.Replace("Hello", null, "");
    //
    //
    

    enter image description here

    但是,如果我编写自己的方法(如MyRegex.MyReplace)并引发异常,则错误消息会标记引发异常的行:

    public static class MyRegex
    {
        public static string MyReplace(string input, string pattern, string replacement)
        {
            if (pattern == null)
            {
                throw new Exception("Pattern must not be null.");
            }
            else
            {
                return Regex.Replace(input, pattern, replacement);
            }
        }
    }
    

    方法调用:

    //
    //
    string str = MyRegex.MyReplace("Hello", null, "");
    //
    //
    

    enter image description here

    如何在一个方法中抛出异常,并在调用该方法的位置(如罐装方法)标记错误消息,而不是在抛出异常的位置?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Gabriel Luci    7 年前

    你看不到里面的任何代码 Regex.Replace ,因此它只显示代码中调用它的行。

    但是因为 throw new Exception()

    如果您构建了一个DLL并在另一个项目中使用它(并且没有复制.pdb文件),那么它的行为将与您的 例如,由于新项目无法看到DLL中的源代码。