在我们正在开发的应用程序中,当发生违反业务规则的情况时,我们会引发自定义异常来处理这种情况。自定义异常是专门为解决应用程序中的独特场景而创建的异常。为了创建自定义异常,我们从 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中文网其他相关文章!