為了不讓這個問我的人說我只是XXXX(找不到好一點的形容詞)...所以我就上網找了一下大師們的文章,看看為啥要這樣寫...
(那隻很會跳的...我就是說你阿~~哈哈~~)
言歸正傳...
問題就是...在try catch中,如果用到了Throw,為啥不用Throw ex而只用Throw呢?
剛剛在一個Blog(Daniel Turini's Lair)上面找到了這一篇文章 - Exception Handling Best Practices in .NET
http://dturini.blogspot.com/2005/02/exception-handling-best-practices-in.html
雖然已經是2005年的文章了,但是我想以目前的.net架構來看,應該還是大同小異吧!因為我覺得那是一個通則...對於程式錯誤處理的通則...
這篇文章裡面其時已經寫的很詳細了...
而為了讓我那位很會跳的朋友可以很快的得到答案,所以我就將它要的答案節錄下來摟~~
Don't clear the stack trace when re-throwing an exception
The stack trace is one of the most useful information that an exception carries. Often, we need to put some exception handling on catch blocks (e.g., to rollback a transaction) and re-throw the exception. See the right (and the wrong) way of doing it:
The wrong way:
try
{
// Some code that throws an exception
}
catch (Exception ex)
{
// some code that handles the exception
throw ex;
}
Why is this wrong? Because, when you examine the stack trace, the point
of the exception will be the line of the "throw ex;", hiding the real
error location. Try it.
try
{
// Some code that throws an exception
}
catch (Exception ex)
{
// some code that handles the exception
throw;
}
What has changed? Instead of "throw ex;", which will throw a new
exception and clear the stack trace, we have simply "throw;". If you
don't specify the exception, the throw statement will simply rethrow
the very same exception the catch statement caught. This will keep your
stack trace intact, but still allows you to put code in your catch
blocks.
Thanks very much..
回覆刪除解了我多年來的疑惑...