在我們正在開發的應用程式中,當發生違反業務規則的情況時,我們會引發自訂異常來處理這種情況。自訂異常是專門為解決應用程式中的獨特場景而創建的異常。為了建立自訂異常,我們從 C# 中的 ApplicationException 或 Exception 類別衍生出一個新類別。 ApplicationException 類別從 .NET v1.0 版本開始包含在 .NET Framework 中,旨在用作 C# 中自訂例外類別的基底類別。
下面給出的是提到的例子:
C# 程序,示範在程式中使用自訂異常。
代碼:
using System; //a namespace called user defined is defined namespace UserDefined { //a class called test weather is defined class Testweather { //main method is called static void Main(string[] args) { //an instance of the class temperat is defined Temperat tem = new Temperat(); try { //the show method of temperat class is called using the instance of the temperat class tem.show(); } catch(WeatheriscoldException e) { Console.WriteLine("The weather is cold Exception: {0}", e.Message); } Console.ReadKey(); } } } //a custom exception class called Weather is cold Exception class is created which is thrown if the weather is cold public class WeatheriscoldException: Exception { public WeatheriscoldException(string message): base(message) { } } //a class called temperat is defined public class Temperat { //a variable called temp is defined and assigned to zero int temp = 0; //a method called show is defined public void show() { //the temperature is checked to determine the weather if(temp == 0) { throw (new WeatheriscoldException("The temperature is found to be zero and hence the weather is cold")); } else { Console.WriteLine("The Temperature is: {0}", temp); } } }
輸出:
說明:
C# 程序,示範在程式中使用自訂異常。
代碼:
using System; //a namespace called exception handling is defined namespace ExceptionHandling { //The custom exception class called odd num exception class is created by inheriting the exception class public class OddNumException : Exception { //The property message is being overridden here public override string Message { get { return "There cannot be an odd divisor"; } } } //a class called check is defined class check { //main method is called static void Main(string[] args) { //three integer variables are defined int a, b, c; Console.WriteLine("Please enter two numbers and type of the numbers must be integer:"); a = int.Parse(Console.ReadLine()); b = int.Parse(Console.ReadLine()); try { //checking if the divisor is an odd number or an even number if (b % 2 > 0) { //exception is thrown if the divisor is an odd number throw new OddNumException(); } c = a / b; Console.WriteLine(c); } catch (OddNumException two) { Console.WriteLine(two.Message); } Console.WriteLine("The program ends here"); Console.ReadKey(); } } }
輸出:
說明:
以下是提到的優點:
以上是C# 中的自訂異常的詳細內容。更多資訊請關注PHP中文網其他相關文章!