[英]Throwing exceptions in ASP.NET C#
只是說throw;
之間有區別嗎throw;
並throw ex;
假設ex
是你正在捕捉的例外嗎?
throw ex;
將擦除你的堆棧跟蹤。 除非你想清除堆棧跟蹤,否則不要這樣做。 只需使用throw;
這是一個簡單的代碼片段,有助於說明差異。 不同之處在於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
你有兩個選擇; 或拋出原始例外作為新例外的一個例外。 根據您的需要而定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.