In C# how do I define my own Exceptions?

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

In C# how do I define my own Exceptions?

8条回答
  •  孤街浪徒
    2020-12-08 00:25

    You can create custom exception by using "Exception" class as base class

    public class TestCustomException: Exception
    {  
    
      public TestCustomException(string message, Exception inner)
        : base(message, inner)
      {
    
      } 
    }
    

    Complete Console Example

    class TestCustomException : Exception
    {
    
        public TestCustomException(string message) : base(message)
        {
            this.HelpLink = "Sample Link details related to error";
            this.Source = "This is source of Error";
        }
    
    }
    
    class MyClass
    {
        public static void Show()
        {
            throw new TestCustomException("This is Custom Exception example in C#");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                MyClass.Show();
            }
            catch (TestCustomException ex)
            {
                Console.WriteLine("Error Message:-" + ex.Message);
                Console.WriteLine("Hyper Link :-" + ex.HelpLink);
                Console.WriteLine("Source :- " + ex.Source);
                Console.ReadKey();
            }
        }
    }
    

    Source : Creating C# Custom Exception (With Console application example)

提交回复
热议问题