In C# how do I define my own Exceptions?

前端 未结 8 2054
北荒
北荒 2020-12-07 23:51

In C# how do I define my own Exceptions?

相关标签:
8条回答
  • 2020-12-08 00:42

    Definition:

    public class CustomException : Exception
    {
       public CustomException(string Message) : base (Message)
       {
       }
    }
    

    throwing:

    throw new CustomException("Custom exception message");
    
    0 讨论(0)
  • 2020-12-08 00:43

    You can define your own exception.

    User-defined exception classes are derived from the ApplicationException class.

    You can see the following code:

    using System;
    namespace UserDefinedException
    {
       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: ApplicationException
    {
       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);
          }
       }
    }
    

    and for throwing an exception,

    You can throw an object if it is either directly or indirectly derived from the System.Exception class

    Catch(Exception e)
    {
       ...
       Throw e
    }
    
    0 讨论(0)
提交回复
热议问题