asp.net C # 's exception handling mechanism program code

Source: Internet
Author: User
Tags error handling error status code exception handling finally block static class

What a perfect application and a skilled programmer can never make a mistake. Rather than pursuing the perfect, error-free code, it's probably the most valuable thing to do before releasing a program that might have foreseen exceptions. So how does C # handle exceptions? First, we start with the most common anomaly:

Using the try-catch-finally block to catch exceptions, the basic format is as follows:

  code is as follows copy code


Try
 {
    //Get and use resources, may appear exceptions
 
 catch (dividebyzeroexception de)
 {
 
 catch (ArithmeticException ae)
 {
 }
 catch (Exception e)
 {
    //capture and handle exceptions. When multiple exceptions occur and there is an inheritance relationship between the exception classes (dividebyzeroexception==>arithmeticexception==>exception),
     The  //capture order is a subclass before the base class is
 }
 finally
 {
    //No matter what the situation is ( The code for the block (such as closing a file) is executed even if it is return in a catch block
    //It is also necessary to use any break, continue in the finally block, Return exit is illegal.
 }


 

Asp. NET exception handling

In addition to the above try-catch-finally processing methods, there are three ways to catch exceptions:

1. Page-level error handling (via Page_Error event)

  code is as follows copy code
protected void Page_Error (object sender, EventArgs e)
{
    string errormsg = String.Empty;
  & nbsp Exception currenterror = Server.GetLastError ();
    errormsg + = "System error:<br/>";
    errormsg + = "Error Address:" + Request.url + "<br/>";
    errormsg + = "error message:" + currenterror.message + "<br/>";
    Response.Write (errormsg);
    Server.ClearError ()//clear exception (otherwise the global Application_Error event will be thrown)
}

2. Application-level (Global.asax) error handling (via Application_Error event)

The code is as follows Copy Code
protected void Application_Error (object sender, EventArgs e)
{
    Exception ex = Server.GetLastError ();
& nbsp;   Exception IEX = ex. innerexception;
    String errormsg = String.Empty;
    string particular = String.Empty;
    if (IEX!= null)
    {
        ErrorMsg = IEX. message;
        particular = IEX. StackTrace;
   }
    Else
    {
        errormsg = ex. message;
        particular = ex. StackTrace;
   }
   //addlog (errormsg, particular);
    Server.ClearError ()//Finish cleaning the exception in time
}

3. Application Configuration (Web.config)

The code is as follows Copy Code
<system.web>
<!--mode has three values: On,off,remoteonly,defaultredirect url--> with error redirection
<customerrors mode= "on" defaultredirect= "errorpage.htm" >
<!--statuscode Error status code, redirect error redirect Url-->
<error statuscode= "403" redirect= "noaccess.htm"/>
<error statuscode= "404" redirect= "filenofound.htm"/>
</customErrors>
</system.web>

WinForm Application Exception Handling

In WinForm applications, how do you implement global exception handling in addition to the try-catch-finally approach? Because there is no Application_Error event, it can be done by way of a delegate.

The code is as follows Copy Code

Internal class Threadexceptionhandler
{
Implementing Error Exception Events
public void Application_threadexception (object sender, Threadexceptioneventargs e)
{
Try
{
Exit the application if the user clicks "Abort"
DialogResult result = Showthreadexceptiondialog (e.exception);
if (result = = Dialogresult.abort)
{
Application.exit ();
}
}
Catch
{
Try
{
MessageBox.Show ("Serious error", "Serious error", MessageBoxButtons.OK, Messageboxicon.stop);
}
Finally
{
Application.exit ();
}
}
}
Private DialogResult Showthreadexceptiondialog (Exception e)
{
String errormsg = "error message: TT" + e.message + "tt" + e.gettype () + "tt" + e.stacktrace;
Return MessageBox.Show (errormsg, "Application Error", Messageboxbuttons.abortretryignore, Messageboxicon.stop);
}
}
Static Class Program
{
<summary>
The main entry point is for the application.
</summary>
[STAThread]
static void Main ()
{
Threadexceptionhandler handler = new Threadexceptionhandler ();
Application.ThreadException + = new ThreadExceptionEventHandler (handler. Application_threadexception);
Application.enablevisualstyles ();
Application.setcompatibletextrenderingdefault (FALSE);
Application.Run (New Frmevent ());
}
}
public partial class Frmevent:form
{
private void Btnexception_click (object sender, EventArgs e)
{
throw new InvalidOperationException ("Invalid operation exception!") ");
}
}
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.