creating my own exceptions c#

后端 未结 4 1666
萌比男神i
萌比男神i 2020-12-24 07:43

Following examples in my C# book and I came across a book example that doesn\'t work in Visual Studio. It deals with creating your own exceptions, this one in particular is

4条回答
  •  感情败类
    2020-12-24 08:15

    Exception is just a class like many other classes in .Net. There're, IMHO, two tricky things with user defined exceptions:

    1. Inherit your exception class from Exception, not from obsolete ApplicationException
    2. User defined exception should have many constructors - 4 in the typical case

    Something like that:

    public class NegativeNumberException: Exception {
      /// 
      /// Just create the exception
      /// 
      public NegativeNumberException()
        : base() {
      }
    
      /// 
      /// Create the exception with description
      /// 
      /// Exception description
      public NegativeNumberException(String message)
        : base(message) {
      }
    
      /// 
      /// Create the exception with description and inner cause
      /// 
      /// Exception description
      /// Exception inner cause
      public NegativeNumberException(String message, Exception innerException)
        : base(message, innerException) {
      }
    
      /// 
      /// Create the exception from serialized data.
      /// Usual scenario is when exception is occured somewhere on the remote workstation
      /// and we have to re-create/re-throw the exception on the local machine
      /// 
      /// Serialization info
      /// Serialization context
      protected NegativeNumberException(SerializationInfo info, StreamingContext context)
        : base(info, context) {
      }
    }
    

提交回复
热议问题