Dot-Net

拋出特定異常子類的目的是什麼?

  • September 6, 2021

為什麼最好拋出這個異常

Throw New DivideByZeroException("You can't divide by zero")

在這個一般的:

Throw New Exception("You can't divide by zero")

在這個特定的例子中獲得了什麼優勢?消息已經說明了一切。從 Exception 基類繼承的標準子類是否有與基類不同的方法?我沒有見過一個案例,但我必須承認我傾向於拋出基本異常。

異常的類型允許異常的處理程序對其進行過濾。如果您拋出的只是類型的異常,Exception處理程序如何知道要擷取哪些異常以及允許哪些異常向上傳播呼叫堆棧?

例如,如果你總是拋出Exception

void Foo(string item) {
 try {
   if (Bar(item)) { 
     Console.WriteLine("BAR!");
   }
 } catch (Exception e) {
   Console.WriteLine("Something bad?");
 }
}

bool Bar(string item) {
 if (item == null) {
   throw new Exception("Argument is null!");
 }

 return Int32.Parse(item) != 0;
}

呼叫者如何Foo知道是否發生了空異常或是否Int32.Parse()失敗?它必須檢查拋出異常的類型(或進行一些討厭的字元串比較)。

ThreadAbortException如果你得到一個或OutOfMemoryException它可能發生在你不會期望異常的地方,那就更令人擔憂了。在這些情況下,如果您的擷取程式碼僅擷取Exception,您可能會掩蓋這些(重要)異常並損壞您的程序(或系統)狀態。

範常式式碼應為:

void Foo(string item) {
 try {
   if (Bar(item)) { 
     Console.WriteLine("BAR!");
   }
 } catch (ArgumentNullException ae) {
   Console.WriteLine("Null strings cannot be passed!");
 } catch (FormatException fe) {
   Console.WriteLine("Please enter a valid integer!");
 }
}

bool Bar(string item) {
 if (item == null) {
   throw new ArgumentNullException("item");
 }

 return Int32.Parse(item) != 0;
}

引用自:https://stackoverflow.com/questions/3980497