代码之家  ›  专栏  ›  技术社区  ›  Chris Westbrook

在ASP.NET C中引发异常#

  •  24
  • Chris Westbrook  · 技术社区  · 16 年前

    只是说 throw; throw ex; 假设 ex 你要抓住的例外吗?

    3 回复  |  直到 16 年前
        1
  •  42
  •   GEOCHET S.Lott    15 年前

    throw ex; 将擦除StackTrace。除非要清除stacktrace,否则不要执行此操作。只使用 throw;

        2
  •  18
  •   Eric Schoonover thSoft    16 年前

    下面是一个简单的代码片段,它将有助于说明差异。不同的是,throw-ex将重置堆栈跟踪,就像行一样” throw ex; “是异常的来源。

    代码:

    using System;
    
    namespace StackOverflowMess
    {
        class Program
        {
            static void TestMethod()
            {
                throw new NotImplementedException();
            }
    
            static void Main(string[] args)
            {
                try
                {
                    //example showing the output of throw ex
                    try
                    {
                        TestMethod();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
    
                Console.WriteLine();
                Console.WriteLine();
    
                try
                {
                    //example showing the output of throw
                    try
                    {
                        TestMethod();
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
    
                Console.ReadLine();
            }
        }
    }
    

    输出(注意不同的堆栈跟踪):

    System.NotImplementedException: The method or operation is not implemented.
    at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 23

    System.NotImplementedException:未实现方法或操作。
    at StackOverflowMess.Program.TestMethod() in Program.cs:line 9
    at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 43

        3
  •  2
  •   user1333    15 年前

    您有两个选项:抛出;或者将原始异常作为新异常的innerException抛出。取决于你需要什么。