C # Summary of custom exceptions and strict adherence to several principles

Source: Internet
Author: User

All Exception types in C # are inherited from System. Exception. That is to say, System. Exception is the base class of all Exception classes. In general, Its Derived classes are divided into two types:
1. SystemException class: All CLR exception types are derived from SystemException.
2. ApplicationException class: this class is triggered by a user program and is used to derive a custom exception type. It is generally not directly instantiated.

Several principles should be strictly followed when creating custom exception classes
1. Declare serializable (used for serialization, of course, if you do not need serialization. So it can not be declared as serialized)
2. Add a default constructor.
3. Add the constructor containing the message
4. Add a constructor containing message and internal exception type parameters.
5. Add a constructor for parameters related to serialization information.
Copy codeThe Code is 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 Serializable because it is written to a file
Public class PayOverflowException: ApplicationException // triggered by a user program, used to derive a custom exception type
{
/// <Summary>
/// Default constructor
/// </Summary>
Public PayOverflowException (){}
Public PayOverflowException (string message)
: Base (message ){}
Public PayOverflowException (string message, Exception inner)
: Base (message, inner ){}
// Public PayOverflowException (System. Runtime. Serialization. SerializationInfo info,
// System. Runtime. Serialization. StreamingContext context)
//: Base (info, context ){}
}
Internal class Employee
{
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 virtual method of GiveBunus for different Derived classes to overload
/// </Summary>
/// <Param name = "amount"> bonus amount </param>
Public virtual void GiveBunus (int amount)
{
// Record the previous value with a temporary variable
Var pay = CurrPay;
This. CurrPay + = amount;
If (CurrPay> 10000)
{
// If an exception occurs, restore the value of CurrPay,
// And throw an exception. An exception is caught by an external program.
This. CurrPay = pay;
Var ex = new PayOverflowException ("The employee's max pay shoshould be no more than 10000 .");
Throw ex;
}
}
}
Class Program
{
Static void Main (string [] args)
{
Console. WriteLine ("***** create an Employee object and catch exceptions with try/catch *****");
Var emp = new Employee (10001, "Yilly", 8000 );
Try
{
Emp. GiveBunus (3000 );
}
Catch (PayOverflowException ex)
{
Console. WriteLine ("exception information: {0} \ n occurs in the {2} method of the {1} class", ex. Message,
Ex. TargetSite. DeclaringType, ex. TargetSite. Name );
Try
{
Var file = new FileStream (@ "c: \ customerexception.txt", FileMode. Create );
// *** The code written to the file for exception information is omitted...
// Write data in serialization Mode
BinaryFormatter bf = new BinaryFormatter ();
Bf. Serialize (file, ex );
File. Close ();
// Write data 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 worth noting that: The PayOverflowException (string message, Exception inner) constructor is called during instantiation,
If other programs in this program are called, you can view internal exceptions through the Message attribute of. InnerExcetpion.

Related Article

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.