Exception 的 StackTrace 信息的丢失

    今天从CodeGuru上看到了一片文章Throwing Exceptions: Will You be Able to Catch What You Expect?

   做了一个实验,现在贴出程序和运行效果:

实验一: ExeceptionCatch 中的 catch块直接使用throw ex

 

static   void  Main( string [] args)
        
... {
            
try
            
...{
                ExceptionCatch();
            }

            
catch (Exception ex)
            
...{
                Console.WriteLine(ex.StackTrace);
                Console.ReadLine();
            }

        }


        
public   static   void  ExceptionCatch()
        
... {
            
try
            
...{
                ExceptionThrow();
            }

            
catch (Exception ex)
            
...{
                
throw ex;
            }

        }


        
public   static   void  ExceptionThrow()
        
... {
            
throw new Exception();
        }

运行结果是:

 

   at ExceptionTest.Program.ExceptionCatch()  in  D:myfileVisual Studio  2005 Pro
jectsExceptionTestExceptionTestProgram.cs:line 
30
   at ExceptionTest.Program.Main(String[] args) 
in  D:myfileVisual Studio  2005
ProjectsExceptionTestExceptionTestProgram.cs:line 
13

实验二: ExeceptionCatch 中的 catch块直接使用throw

 

static   void  Main( string [] args)
        
... {
            
try
            
...{
                ExceptionCatch();
            }

            
catch (Exception ex)
            
...{
                Console.WriteLine(ex.StackTrace);
                Console.ReadLine();
            }

        }


        
public   static   void  ExceptionCatch()
        
... {
            
try
            
...{
                ExceptionThrow();
            }

            
catch (Exception)
            
...{
                
throw;
            }

        }


        
public   static   void  ExceptionThrow()
        
... {
            
throw new Exception();
        }

运行结果是:

 

   at ExceptionTest.Program.ExceptionThrow()  in  D:myfileVisual Studio  2005 Pro
jectsExceptionTestExceptionTestProgram.cs:line 
36
   at ExceptionTest.Program.ExceptionCatch() 
in  D:myfileVisual Studio  2005 Pro
jectsExceptionTestExceptionTestProgram.cs:line 
30
   at ExceptionTest.Program.Main(String[] args) 
in  D:myfileVisual Studio  2005
ProjectsExceptionTestExceptionTestProgram.cs:line 
13


 由此可见,如果在使用throw ex的话将会导致一个新的Exception被抛出,使得StackTrace的信息会丢失,这样的话我们获得的异常信息将会是最后一个重新抛出异常的StackTrace信息。如果我们使用的是throw的话,系统将会重新抛出原来的异常,这样的话我们就不会丢失StackTrace信息了。

你可能感兴趣的:(exception)