157 recommendations for writing high-quality code to improve C # programs--Recommendation 68: Derive exceptions from System.Exception or other common basic exceptions

Source: Internet
Author: User

Recommendation 68: Derive exceptions from System.Exception or other common basic exceptions

Microsoft recommends that you derive an exception from System.Exception or one of the other common basic exceptions. Entering exception in Visual Studio and pressing the shortcut key Tab,vs automatically creates a custom exception class:

[Serializable] Public classmyexception:exception {//        //for guidelines regarding the creation of new exception types, see//    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/ Cpconerrorraisinghandlingguidelines.asp        // and//    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp        //         Publicmyexception () {} PublicMyException (stringMessage):Base(message) {} PublicMyException (stringMessage, Exception inner):Base(message, inner) {}protectedmyexception (SerializationInfo info, StreamingContext context):Base(info, context) {}}

This is a standard custom exception, and it also tells you that the exception you create must be serializable, because you must ensure that the exception is able to cross the AppDomain boundary.

If you need to derive a custom exception from a base exception, it is similar to the declaration:

    [Serializable]    publicclass Myexception:ioexception

In general, the above description already satisfies your common need for custom exceptions, but another requirement is that you might want to format the exception message. For example, to design a custom encryption exception for an exam system: paperencryptexception, we need to format some exception information. Therefore, you must override the message property of the (override) exception class as follows:

[Serializable] Public classpaperencryptexception:exception, ISerializable {Private ReadOnly string_paperinfo;  Publicpaperencryptexception () {} PublicPaperencryptexception (stringMessage):Base(message) {} PublicPaperencryptexception (stringMessage, Exception inner):Base(message, inner) {} PublicPaperencryptexception (stringMessagestringpaperinfo):Base(message) {_paperinfo=Paperinfo; }         PublicPaperencryptexception (stringMessagestringPaperinfo, Exception inner):Base(message, inner) {_paperinfo=Paperinfo; }        protectedPaperencryptexception (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context):Base(info, context) {} Public Override stringMessage {Get            {                return Base. Message +" "+_paperinfo; }        }         Public Override voidGetObjectData (SerializationInfo info, StreamingContext context) {info. AddValue ("Args", _paperinfo); Base.        GetObjectData (info, context); }    }

There are two distinct differences between paperencryptexception and MyException:

1) implements the interface ISerializable.

2) overridden the method GetObjectData.

This is because we have defined a new field _paperinfo for Paperencryptexception. To ensure that the newly defined field can also be serialized, you must have the exception type implement the ISerializable interface, and you need to add the field to the SerializationInfo parameter of the GetObjectData method.

The test code is as follows:

            Try             {                thrownew paperencryptexception (" cryptographic Quiz failed ""  student id:123456");            }             Catch (paperencryptexception Err)            {                Console.WriteLine (err. Message);            }

Output:

"Cryptographic quiz failed student id:123456"

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 68: Derive exceptions from System.Exception or other common basic exceptions

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.