假設ex
是您捕捉到的異常,只是說throw;
和throw ex;
是否有區別?在ASP.NET C中拋出異常#
23
A
回答
41
throw ex;
將清除您的堆棧跟蹤。除非你想清除堆棧跟蹤,否則不要這樣做。只需使用throw;
2
你有兩個選擇拋出;或者拋棄原來的例外作爲對新例外的一種內化。取決於你需要什麼。
18
下面是一個簡單的代碼片段,它有助於說明差異。區別在於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: The method or operation is not implemented.
at StackOverflowMess.Program.TestMethod() in Program.cs:line 9
at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 43
相關問題
- 1. 在C++中拋出異常異常
- 2. C#拋出異常
- 3. C++異常拋出
- 4. C#拋出異常
- 5. ASP.NET Web API拋出異常
- 6. ASP.NET MVC - 拋出異常?
- 7. Asp.Net MVC Cookie拋出異常
- 8. 通過asp.net拋出異常
- 9. ASP.NET MVC3:TryUpdateModel拋出異常
- 10. C++/C#異常拋出
- 11. 爲什麼在java中拋出異常而在C++中拋出異常?
- 12. StringToByteArray()在C#2.0中拋出異常
- 13. 在C#中拋出異常,警衛
- 14. GoogleWebAuthorizationBroker在C#中拋出異常#
- 15. 拋出異常拋出異常
- 16. 在Java中拋出自定義異常與在異常中拋出異常
- 17. 魔術異常拋出拋出異常
- 18. C#/ ASP - 異常拋出
- 19. Objective-C異常未拋出
- 20. 拋出異常c#高級
- 21. 拋出異常Xamarin c#
- 22. 拋出異常的C#
- 23. SqlConnection.Open拋出異常C#
- 24. 異常拋出鎖c#2
- 25. WaitForExit()拋出異常c#
- 26. C# - 拋出異常類
- 27. C#委託拋出異常
- 28. C++ debugger_hook_dummy拋出異常
- 29. C#string.Format拋出異常
- 30. asp.net中的FileUpload控件拋出異常
有很多情況下'throw ex'有用嗎? – 2008-09-17 23:47:46