How to customize your own exceptions in C #

Source: Internet
Author: User

All exception types in C # inherit from System.Exception, meaning that System.Exception is the base class for all exception classes. In general, the derived classes are divided into two types:
1. SystemException class: All CLR-supplied exception types are derived by SystemException.
2. ApplicationException class: Thrown by a user program, used to derive a custom exception type, typically not instantiated directly.

Creating custom exception classes should follow several principles
1. Declare serializable (for serialization, of course if you do not need serialization.) Then it can not be declared as serializable)
2. Add a default constructor
3. Add a constructor that contains a message
4. Add a constructor that contains a message, and an internal exception type parameter
5. Add a constructor that serializes the information-related parameters.
Copy the code code as follows:

Using system;using system.collections.generic;using system.linq;using system.text;using System.IO;using System.runtime.serialization.formatters.binary;namespace consoleapplication3{[Serializable]//declared as serializable because to write a file in Pu Blic class payoverflowexception:applicationexception//is thrown by the user program to derive the custom exception type {///<summary>///default constructor///</summary> public payoverflowexception () {} public payoverflowexception (String messag E): Base (Message) {} public payoverflowexception (String message, Exception inner): Base (Mes Sage, inner) {}//public payoverflowexception (System.Runtime.Serialization.SerializationInfo info,/ /System.Runtime.Serialization.StreamingContext context)//: Base (info, context) {}} internal class employ        EE {public int ID {get; set;}        public string Name {get; set;}     <summary>//Current pay//</summary>   public int Currpay {get; set;}            Public employee () {} public employee (int ID, string name, int currpay) {this.id = ID; This.            name = name; This.        Currpay = Currpay; }///<summary>///Define a Givebunus virtual method to be overloaded by different derived classes///</summary>//<param Nam            E= "Amount" > Bonus amount </param> public virtual void Givebunus (int amount) {//record the value before incrementing with a temporary variable            var pay = Currpay; This.            Currpay + = amount;                if (Currpay > 10000) {//exception occurs, the value of Currpay is restored,//And an exception is thrown, and the external program catches a minor exception This.                Currpay = pay;                var ex = new Payoverflowexception ("The employee ' s Max pay should is no more than 10000.");            Throw ex; }}}} class program {static void Main (string[] args) {Console.WriteLine ("* * * *            Build Employee object and use Try/catch to catch the exception * * * *;var emp = new Employee (10001, "yilly", 8000); try {emp.            Givebunus (3000); } catch (Payoverflowexception ex) {Console.WriteLine ("Exception information: {0}\n occurred in {1} class {2} method", EX.M Essage, ex. Targetsite.declaringtype, ex.                Targetsite.name);                    try {var file = new FileStream (@ "C:\customerexception.txt", FileMode.Create); Exception information write code in file omitted ...//serialized write BinaryFormatter bf = new Binaryformatt                    ER (); Bf.                    Serialize (file, ex); File.                    Close (); Write in bytes//byte[] buffer = System.Text.Encoding.Default.GetBytes (ex.                    Message);                    int leng = 0; Leng = buffer.                    GetLength (0); File.                    Write (buffer, 0, Leng); File.                Close ();     } catch (Exception Ex1)           {var inner = new Payoverflowexception (ex.                    Message, EX1);                throw inner; }            }        }    }}


It is important to note that the Payoverflowexception (string message, Exception inner) constructor is called when the instantiation is instantiated.
If this program if there are other programs in the call, you can pass. Innerexcetpion the message property to view the inner exception.

How to customize your own exceptions in C #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.