C # custom exception handling (custom exceptions)

Source: Internet
Author: User

Http://www.cnblogs.com/winnerlan/archive/2008/05/24/1206644.html

For the. NET class, the general exception class system. Exception
Derived from system. object. There are also many defined exception classes (such as system. systemexception and system. applicationexception) that are derived from
System. exception class. System. applicationexception
A class is an exception class defined by a third party. If we want to customize the exception class, we should dispatch it.

We need to compile the exception handling program from the perspective of exceptions that may occur, and establish a good exception handling policy in response to possible errors of the program.
During Exception Handling, it is best to use try-catch at all the entrances of the application (event processing function, main function, and thread entry. However, do not add try-catch at the entrance of the program constructor. Because an exception occurs here, it does not have the ability to handle it itself, because it has not been constructed, and can only throw an exception to the outer layer.
However, we cannot blindly use exceptions. In addition, exceptions may affect the program performance to some extent (exceptions in C # generally do not affect the performance ).

// Custom exception class
Public class myexception: applicationexception
{
Public myexception (string message): Base (Message)
{
}

Public myexception (string message, exception innerexception)
: Base (message, innerexception)
{
}
}

Global Exception Handling and multi-thread Exception Handling

Add the delegate of the global exception handling function to application. threadexception
. During multi-thread Exception Handling, an exception occurs in the working thread or auxiliary thread. You can forward the exception to the main thread for exception handling. If there is no notification between threads, exceptions cannot be caught directly. If the exception is not handled in the worker thread or auxiliary thread, the exception will be "lost.

Why do I have to handle all exceptions to the main thread? For example, in winform, we use multiple threads to process interface elements. Once an exception occurs, the exception message is displayed. Then, is MessageBox directly after an exception occurs, or is the message delivered to mainui for unified display? Imagine if the program is complex or has multiple interfaces that use multiple threads to display interface elements, then the former is used, even if we know the exception details, however, it may be difficult to find out what went wrong. However, it is much better to use mainui to display the situation, especially when designing other things (such as multi-language Environments ). Of course, this example is only a small one. The following describes how to implement it:

Using system;
Using system. drawing;
Using system. collections;
Using system. componentmodel;
Using system. Windows. forms;
Using system. Data;
Using system. Threading;

Namespace threadapp
{
Public class frmmain: system. Windows. Forms. Form
{
Private system. Windows. Forms. Button btrun;
///
/// Required designer variables.
///
Private system. componentmodel. Container components = NULL;

Public Delegate void workerthreadexceptionhandlerdelegate (exception E );
Void workerthreadexceptionhandler (exception E)
{
This. Text = "disposed .";
Mainuithreadexceptionhandler (this, new system. Threading. threadexceptioneventargs (e ));
}

Public frmmain ()
{
Initializecomponent ();
}

///
/// Clear all resources in use.
///
Protected override void dispose (bool disposing)
{
If (disposing)
{
If (components! = NULL)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}

Code generated by the Windows Form Designer

///
/// Main entry point of the application.
///
[Stathread]
Static void main ()
{
Application. threadexception + = new threadexceptioneventhandler (mainuithreadexceptionhandler );
Application. Run (New frmmain ());
}

Public static void mainuithreadexceptionhandler (exception E)
{
Mainuithreadexceptionhandler (null, new system. Threading. threadexceptioneventargs (e ));
}

Public static void mainuithreadexceptionhandler (Object sender, threadexceptioneventargs T)
{
MessageBox. Show (T. Exception. message, "exception ",
Messageboxbuttons. OK,
Messageboxicon. Warning );
}


Private void throwexception ()
{
Throw new notimplementedexception ();
}

Private void run ()
{
Try
{
This. Text = "Waiting"; // [Error] The compilation fails in section 2.0. Because it is against our principle-do not operate across threads (the current thread operates on interface thread elements)
Thread. Sleep (2000 );
This. Text = "Throw exception ";
Throwexception ();
This. Text = "finished"; // [Error] (same as above)
}
Catch (exception E)
{

// If multi-thread interoperability is involved,
// You can use begininvoke to implement mutual access between multiple threads.
This. begininvoke (
New workerthreadexceptionhandlerdelegate (
Workerthreadexceptionhandler ),
New object [] {e });}
}

Private void btrun_click (Object sender, system. eventargs E)
{
Threadstart Ts = new threadstart (run );
Thread t = new thread (TS );
T. Start ();

// Throw new notsupportedexception ();
}
}
}

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.