clr via c # exceptions and state management

. 1, System.Exception class --- base class for all exception classes

Message

readonly string Indicate the cause of the abnormal
Data readonly IDictionary A reference to a collection of key-value pairs
Source r/w string Program includes unusual set name
StackTrace r string Before calling all the methods and information contained abnormal
TargetSite r MethodBase Contains the method throws an exception
InnerException r Exception

If the current exception handling an exception is thrown, then figure out what the exceptions are

You can use Exception.GetBaseException to traverse an exception list.

HResult r/w int COM api return value maintenance.

1.1 Exception.GetBaseException method usage

  •         First, create two classes for re-throw an exception:
class SecondLevelException: Exception 
    { public SecondLevelException ( String Message, Inner Exception) // Message used to initialize and InnerExciption exception 
            : Base (Message, Inner) 
        {} 
    } class ThirdLevelException: Exception // Message used to initialize and InnerExciption abnormality 
    { public ThirdLevelException ( String Message, Inner Exception) 
            : Base (Message, Inner) 
        {} 
    }
        
    
        
  
  •       Second, create behavioral approach for throwing exceptions:
    • static void DivideBy0()
              {
                  try
                  {
                      int zero = 0;
                      int ecks = 1 / zero;
                  }
                  catch (Exception ex)
                  {
                      throw new SecondLevelException(
                          "Forced a division by 0 and threw " +
                          "a second exception.", ex);
                  }
              }
      static void Rethrow()
              {
                  try
                  {
                      DivideBy0();
                  }
                  catch (Exception ex)
                  {
                      throw new ThirdLevelException(
                          "Caught the second exception and " +
                          "threw a third in response.", ex);
                  }
              }
  •     Create a test method:
    •  public static void Go()
              {
      
      
                  try
                  {
                      // This function calls another that forces a 
                      // division by 0.
                      Rethrow();
                  }
                  catch (Exception ex)
                  {
                      Exception current;
      
      
                      // This code unwinds the nested exceptions using the 
                      // InnerException property.
                      current = ex;
                      while (current != null)
                      {
                          Console.WriteLine(current.ToString());
                          Console.WriteLine();
                          current.InnerException = Current; // call to the current exception exceptions. 
                      } // Display The Innermost Exception. 
                      Console.WriteLine ( 
                          " Display The Base Exception " + 
                          " the using Method The GetBaseException: \ n- "); 
                      Console.WriteLine ( 
                          . ex.GetBaseException () the ToString ()); 
                  } 
              }
      
                      


  • The test results are given
  • ClrFromCSharp_2_2.LearnException.ThirdLevelException: Caught at The Exception and threw A SECOND, THIRD, in the Response ---> ClrFromCSharp_2_2.LearnException.SecondLevelException:. Forced by Division A 0 and A SECOND, threw Exception ---> System.DivideByZeroException:. Attempt to divide by zero . 
       In ClrFromCSharp_2_2.LearnException.ExceptionRef.DivideBy0 () position of C: \ reps \ ClrFromCSharp \ ClrFromCSharp_2_2 \ LearnException \ ExceptionRef.cs: 62 line number 
       inside the end of the exception stack trace --- --- 
       in ClrFromCSharp_2_2.LearnException.ExceptionRef.DivideBy0 ( ) position of C: \ reps \ ClrFromCSharp \ ClrFromCSharp_2_2 \ LearnException \ ExceptionRef.cs: 66 line 
       () in position C ClrFromCSharp_2_2.LearnException.ExceptionRef.Rethrow: \ reps \ ClrFromCSharp \ ClrFromCSharp_2_2 \ LearnException \ ExceptionRef.cs: line 48 
       - - the end of inner exception stack trace ---
       () In position C ClrFromCSharp_2_2.LearnException.ExceptionRef.Rethrow: \ reps \ ClrFromCSharp \ ClrFromCSharp_2_2 \ LearnException \ ExceptionRef.cs: line number 52 
       in ClrFromCSharp_2_2.LearnException.ExceptionRef.Go () position of C: \ reps \ ClrFromCSharp \ ClrFromCSharp_2_2 \ LearnException \ ExceptionRef.cs: line 19 --- --- from the original exception to be thrown a trace unusual. 
    
    ClrFromCSharp_2_2.LearnException.SecondLevelException: Forced a Division by 0 a SECOND, and threw Exception ---> System.DivideByZeroException.: attempt to divide by zero. 
       In ClrFromCSharp_2_2.LearnException.ExceptionRef.DivideBy0 () position of C: \ reps \ ClrFromCSharp \ ClrFromCSharp_2_2 \ LearnException \ ExceptionRef.cs: 62 line number 
       inside the end of the exception stack trace --- --- 
       in ClrFromCSharp_2_2.LearnException.ExceptionRef.DivideBy0 ( ) location C: \ reps \ ClrFromCSharp \ ClrFromCSharp_2_2 \ LearnException \ ExceptionRef.cs: line 66
       In ClrFromCSharp_2_2.LearnException.ExceptionRef.Rethrow () Location C: \ reps \ ClrFromCSharp \ ClrFromCSharp_2_2 \ LearnException \ ExceptionRef.cs: // a base line number 48 from the original exception to throw an exception.
    
    System.DivideByZeroException: try to divide by zero. 
       In ClrFromCSharp_2_2.LearnException.ExceptionRef.DivideBy0 () position of C: \ reps \ ClrFromCSharp \ ClrFromCSharp_2_2 \ LearnException \ ExceptionRef.cs: // The line number 62 from the first exception to be thrown exception of a base. 
    
    Display The base Exception the using The Method GetBaseException : 
    
    System.DivideByZeroException: try to divide by zero. 
       In ClrFromCSharp_2_2.LearnException.ExceptionRef.DivideBy0 () position of C: \ reps \ ClrFromCSharp \ ClrFromCSharp_2_2 \ LearnException \ ExceptionRef.cs: 62 @ bottom line number of a ex
    • From this we can see that, InnerException, by transfer method Throw Catch block Similarly
    • static void Rethrow()
              {
                  try
                  {
                      DivideBy0();
                  }
                  catch (Exception ex)
                  {
                      throw new ThirdLevelException(
                          "Caught the second exception and " +
                          "threw a third in response.", ex);
                  }
              }
    • Exception.GetBaseException
    • ex.GetBaseException () the ToString ());. . Exception // Get list of exception thrown in front of the first throw of the back.
    • The first definition of exceptions thrown --- most Base, the bottom; the last exception thrown --- Current, the most top.

2, the use of custom exception class and method:

  1.            Define a custom exception class


[Serializable]
    public sealed class Exception<TExceptionArgs> : Exception, ISerializable where TExceptionArgs:ExceptionArgs
    {
        private const string c_args = "args";
        private readonly TExceptionArgs m_args;
        public TExceptionArgs Args { get { return m_args; } }
        public Exception(string message=null,Exception innerException = null) : this(null, message, innerException) { }
        publicException (args TExceptionArgs, String Message = null , the innerException Exception = null ): Base (Message, the innerException) = {m_args args;}
         // This constructor is used to deserialize, since the private class, the constructor is private. 
        [the SecurityPermission (SecurityAction.LinkDemand, the Flags = SecurityPermissionFlag.SerializationFormatter)] // to protection class 
        Private Exception (the SerializationInfo info, StreamingContext context): Base (info, context) 
        { 
            m_args = (TExceptionArgs) info.GetValue (c_args, typeof ( TExceptionArgs)); 
        } 
        [the SecurityPermission (SecurityAction.LinkDemand, the Flags = SecurityPermissionFlag.SerializationFormatter)]
        public override void GetObjectData(SerializationInfo info,StreamingContext context)
        {
            info.AddValue(c_args, m_args);
            base.GetObjectData(info, context);
        }
        public override string Message
        {
            get
            {
                string baseMsg = base.Message;
                return (m_args == null) ? baseMsg : string.Format("{0} ({1})", baseMsg, m_args.Message);
            }
        }
        public override bool Equals(object obj)
        {
            Exception<TExceptionArgs> other = obj as Exception<TExceptionArgs>;
            if (other == null) return false;
            return object.Equals(m_args, other.m_args) && base.Equals(obj);
        }
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }
  1. The exception class inherits and Exception Iserializable. Class and implements serialization and deserialization
  2. This class can carry a class parameter information.
[Serializable]
    public abstract class ExceptionArgs
    {
        public virtual String Message { get { return string.Empty; } }
    }


3, to establish their own ExceptionArgs derived class, used to carry the abnormal information.

public sealed class DiskFullExceptionArgs : ExceptionArgs
    {
        public string Path { get; }
        public DiskFullExceptionArgs(string path)
        {
            Path = path;
        }
        public override string Message => Path ?? base.Message;
    }

    4, use:

 public static void GoCustomException()
        {
            try
            {
                throw new Exception<DiskFullExceptionArgs>(new DiskFullExceptionArgs(@"c:\"), "disk is full");
            }
            catch(Exception<DiskFullExceptionArgs> e)
            {
                Console.WriteLine("the Exception Message is {0}", e.Message);//调用类e.Message
                Console.WriteLine("the ExceptionArgs Message is {0}", e.Args.Message);//调用类e.Args.Message
            }
        }

     5 results

the Exception Message is disk is full (c:\)
the ExceptionArgs Message is c:\

Guess you like

Origin www.cnblogs.com/frogkiller/p/12291485.html