Valid C # create a specific exception class for the Application

Source: Internet
Author: User
An exception is a mechanism for reporting errors. It can handle errors away from errors. All information about the error must be included in the exception object. When an error occurs, you may want to convert the underlying error into a detailed application error without losing any information about the error. You need to carefully consider how to create special exception classes in the C # application. The first step is to understand when and why to create a new exception class, and how to construct inherited exception information. When developers use your library to write catch statements, they differ in the same behavior based on exceptions during special periods. Different exception classes can be processed differently: Try {
Foo ();
Bar ();
} Catch (MyFirstApplicationException e1)
{
FixProblem (e1 );
} Catch (AnotherApplicationException e2)
{
ReportErrorAndContinue (e2 );
} Catch (YetAnotherApplicationException e3)
{
ReportErrorAndShutdown (e3 );
} Catch (Exception e)
{
ReportGenericError (e );
}
Finally
{
CleanupResources ();
}

Different catch statements can exist due to different runtime exceptions. You, as the author of the database, must create or use different exception classes to handle different things in an exception catch statement. If this is not the case, your users have only one boring choice. When an exception is thrown, You can suspend or stop the application. This is of course the least work, but it is impossible to win reputation from users. Or they can get an exception and try to determine whether the error can be corrected:Try {
Foo ();
Bar ();
} Catch (Exception e)
{
Switch (e. TargetSite. Name)
{
Case "Foo ":
FixProblem (e );
Break;
Case "Bar ":
ReportErrorAndContinue (e );
Break;
// Some routine called by Foo or Bar:
Default:
ReportErrorAndShutdown (e );
Break;
}
} Finally
{
CleanupResources ();
}

This is far less attractive than using multiple catch statements. This is a very fragile code: if the name is modified normally, it will be destroyed. If you move the function call that causes the error and put it in a shared tool function, it will also be destroyed. If an exception occurs on a deeper stack, the structure becomes more vulnerable.

Before discussing this topic in depth, let me first describe two things that cannot be promised. First, the exception cannot handle all the exceptions you encounter. This is not a solid guidance method, but I like to throw exceptions for error conditions. If these conditions are not handled immediately or reported, more serious problems may occur in the future. For example, a data integrity error in the database should produce an exception. This problem becomes more serious if it is ignored. However, when writing data to the user's window location fails, it is not as if a series of problems will occur later. It is enough to return an error code to indicate failure.

Second, writing a throw statement does not mean that a new exception class will be created at this time. I recommend that you create more exceptions, rather than just a few common natural exceptions: It seems that when someone throws an Exception, it only takes a few minutes to get rid of System. Exception. Unfortunately, only the minimum help information can be provided to process the calling code. On the contrary, consider creating some necessary exception classes to let the calling code understand what the situation is and provide the best opportunity to restore it.

Again: in fact, we need to create different exception classes, and the only reason is that it is easier for your users to write catch statements to handle errors. View and analyze these error conditions to see which types of errors can be put into a recoverable behavior, and then create a specified exception class to handle these behaviors. Can your application be recovered from a file or directory loss error? Can it be recovered from insufficient security permissions? What if network resources are lost? If you encounter different errors and adopt different recovery mechanisms, you should create new exception classes for different behaviors.

Therefore, now you should create your own exception class. When you create an exception class, you have many responsibilities to complete. You should always derive your Exception class from the System. ApplicationException class, instead of the System. Exception class. You do not need to add too many features to this base class. Different exception classes can be processed in different catch statements.

But do not delete anything from the exception class. The ApplicationException class has four different constructors:// Default constructor
Public ApplicationException ();

// Create with a message.
Public ApplicationException (string );

// Create with a message and an inner exception.
Public ApplicationException (string, Exception );

// Create from an input stream.
Protected ApplicationException (
SerializationInfo, StreamingContext );

When you create a new exception class, you should create this four constructor. Different constructor methods are called to construct an exception in different situations. You can delegate this work to the base class for implementation:Public class MyAssemblyException:
ApplicationException
{
Public MyAssemblyException ():
Base ()
{
}

Public MyAssemblyException (string s ):
Base (s)
{
}

Public MyAssemblyException (string s,
Exception e ):
Base (s, e)
{
}

Protected MyAssemblyException (
SerializationInfo info, StreamingContext cxt ):
Base (info, cxt)
{
}
}
 

The exception parameter required by the constructor is worth discussing. Sometimes, an exception occurs in one of the class libraries you use. Calling the code of your database may obtain the minimum information about possible behavior correction. When you upload parameters from your exception:Public double DoSomeWork ()
{
// This might throw an exception defined
// In the third party library:
Return ThirdPartyLibrary. ImportantRoutine ();
}

When you create an exception, you should provide your own library information. Throw your own detailed exception and include the source exception as its internal exception attribute. You can provide the most additional information you can provide :'Public double DoSomeWork ()
{
Try {
// This might throw an exception defined
// In the third party library:
Return ThirdPartyLibrary. ImportantRoutine ();
} Catch (Exception e)
{
String msg =
String. Format ("Problem with {0} using library ",
This. ToString ());
Throw new DoingSomeWorkException (msg, e );
}
}
}

This new version will create more information where the problem occurs. When you have created an appropriate ToString () method (see Principle 5), you have created an exception object that can fully describe the problem. More, an inline exception shows the root cause of the problem: some information in the third-party library you are using.

This technology is called exception conversion, which converts a bottom layer exception to a more advanced exception. This provides more information about the error. The more information you create about an error, the easier it is to use it for diagnosis and possibly error correction. By creating your own exception classes, you may convert the underlying problems to detailed exceptions. This exception contains detailed application information, this helps you diagnose programs and correct problems as much as possible.

I hope your application does not throw exceptions frequently, but it will happen. If you do not perform any detailed processing, your application may generate a default. Net Framework exception, no matter what error occurs in the method you call. Providing more detailed information will help you and your users diagnose programs and possible correction errors in actual applications. You should create different exception classes only when there are different actions to handle errors. You can create a fully functional exception class by providing constructors supported by all base classes. You can also use the InnerException attribute to carry all error messages of the underlying error conditions.

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.