在 C# 中自定義異常有哪些?
在 C# 中和任何其他程式語言一樣,您可以輕鬆建立使用者定義的異常。使用者定義的異常類衍生自異常類。自定義異常是我們所說的使用者定義異常。
在下面的示例中,建立的異常不是內建異常;它是一個自定義異常 -
TempIsZeroException
您可以嘗試執行以下程式碼來了解如何在 C# 中建立使用者定義的異常。
示例
using System;
namespace Demo {
class TestTemperature {
static void Main(string[] args) {
Temperature temp = new Temperature();
try {
temp.showTemp();
} catch(TempIsZeroException e) {
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException: Exception {
public TempIsZeroException(string message): base(message) {}
}
public class Temperature {
int temperature = 0;
public void showTemp() {
if(temperature == 0) {
throw (new TempIsZeroException("Zero Temperature found"));
} else {
Console.WriteLine("Temperature: {0}", temperature);
}
}
}這將生成以下輸出 -
輸出
TempIsZeroException: Zero Temperature found
廣告
資料結構
網路相關
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP