SlideShare a Scribd company logo
•Error occurred in execution time


 •Abnormal termination of program


 • Wrong execution result




11/19/2012     Presented by: Neelesh Shukla   1
Is it a best practice to handle every
                 error?
  No, it is not best practice to handle every error. It
    degrades the performance.
  You should use Error Handling in any of following
    situation otherwise try to avoid it.
 1.     If you can able to recover error in the catch block
 2.     To write clean-up code that must execute even if
      an exception occur
 3.     To record the exception in event log or sending
      email.
11/19/2012       Presented by: Neelesh Shukla                 2
Exception Handling
         There are three ways to handle exceptions/errors in
                                           ASP.NET

           1) Try-Catch block.              This is also called Structured
                                             Exception Handling (SEH).

           2) Error Events.                 They are page level or application
                                             level error events.

           3) Custom Error Page. This is used for any unhandled
                                  error.
    11/19/2012          Presented by: Neelesh Shukla                          3
1) What is try Block?
  Try Block consist of code that might generate error.


  Try Block must be associated with one or more catch
     block or by finally block.

  Try Block need not necessarily have a catch Block
     associated with it but in that case it must have a finally
     Block associate with it.


11/19/2012        Presented by: Neelesh Shukla                    4
What is catch Block?
  Catch Block is used to recover from error generated in
   try Block.
  In case of multiple catch Block, only the first matching
   catch Block is executed.
  When you write multiple catch block you need to
   arrange them from specific exception type to more
   generic type.
  When no matching catch block are able to handle
   exception, the default behavior of web page is to
   terminate the processing of the web page.

11/19/2012      Presented by: Neelesh Shukla                  5
What is finally Block?
 Finally Block contains the code that always executes, whether
    or not any exception occurs.
   When to use finally Block? - You should use finally block to
    write cleanup code. i.e. you can write code to close files,
    database connections, etc.
   Only One finally block is associated with try block.
   Finally block must appear after all the catch block.
    If there is a transfer control statement such as goto, break or
    continue in either try or catch block the transfer happens
    only after the code in the finally block is executed.
    If you use transfer control statement in finally block, you will
    receive compile time error.
11/19/2012          Presented by: Neelesh Shukla                    6
Example of Try-Catch-Finally
       Try
       {
       --------
       --------
       --------
       }
       Catch(Exception ex)
       {
       -------
       -------
       }
       Finally
       {
       ----
       }
11/19/2012            Presented by: Neelesh Shukla   7
System-Defined Exception
  DivideByZero Exception
  NullReference Exception
  IndexOutOfRange Exception
  ArrayTypeMismatch Exception
  Arithmetic Exception
  Exception etc.




11/19/2012        Presented by: Neelesh Shukla   8
Exception class object properties
  Message: Get the error message.
  Source: Set or get the name of the application or object
   that causes the exception.
  StackTrace: Get a string representation of the frame on
   call stack at the time of current exception thrown.
  TargetSite: Get the current method that throws
   exception.
  InnerException: Get the system.exception instance
   that causes the current exception.

11/19/2012      Presented by: Neelesh Shukla                  9
In general, you will not be able to plan for,
catch and recover from every possible
exception that could occur within a page.
ASP.NET helps by offering two techniques to
handle page-level errors :

  Error Events
  Custom Error Page.




11/19/2012        Presented by: Neelesh Shukla   10
2)Error Events
 They are page level or application level error events:-
  Page_Error()
  Application_Error()




11/19/2012        Presented by: Neelesh Shukla             11
Page_Error()
 private void Page_Error(object sender, EventArgs e)
   {
      Exception ex = Server.GetLastError();
      Response.Write("<h1>An error has occurred</h1>");
      Response.Write("<h2>" + ex.Message + "</h2>");
      Response.Write("<pre>" + ex.StackTrace +
   "</pre>");
      Context.ClearError();
   }
 Note: This event fire if the page control is not disposed.
11/19/2012      Presented by: Neelesh Shukla                  12
Application_Error()
 The Error event of the Application class is fired when an exception is left
   unhandled. The handler is usually found in Global.asax

void Application_Error(object sender, EventArgs e)
  {
      // Code that runs when an unhandled error occurs

    System.Exception ex = Context.Server.GetLastError();

    ExceptionLog.MessageDetails(ex);

    // Code for handling error on Application level

    Response.Write("Handled error from Application <br>");
    Server.ClearError();
  }
Note: In the code above that ClearError() method should always be called after the exception has
   been handled. If the ClearError() has not been cleared, the exception will still show up on the
   client's browser.
    11/19/2012               Presented by: Neelesh Shukla                                     13
3) Custom Error Page
  First change the Application_Error method to the following:
   protected void Application_Error(object sender, EventArgs e)
   {
        System.Exception ex = Context.Server.GetLastError();
        ExceptionLog.MessageDetails(ex);
   }
  Notice that I have removed the Server.ClearError();
  Then add a customErrors section to your web.config file. This
   should be nested within the system.web element
  Add a new custom error page “Error.aspx” into your project to
   display a custom Error page, if any unhandled error occurs.


11/19/2012        Presented by: Neelesh Shukla                     14
<system.web>
      .....
     <customErrors mode="On" defaultRedirect="Error.aspx">
     //<error statusCode="404" redirect="Error404.aspx" />
     </customErrors>
     </system.web>

Note: Details of status code can be found at http://httpstatus.es

 To customize the default error page, one will have to change the default
     configuration settings of the application.
     There are three error modes in which an ASP.Net application can work:

1.         Off Mode
2.         On Mode
3.         RemoteOnly Mode
     11/19/2012         Presented by: Neelesh Shukla                   15
1. When the error attribute is set to "Off", ASP.Net uses
    its default error page for both local and remote users
    in case of an error.
 2. In case of "On" Mode, ASP.Net uses user-defined
    custom error page instead of its default error page for
    both local and remote users. If a custom error page is
    not specified, ASP.Net shows the error page
    describing how to enable remote viewing of errors.
 3. The Error mode attribute determines whether or not
    an ASP.Net error message is displayed. By default, the
    mode value is set to "RemoteOnly".



11/19/2012      Presented by: Neelesh Shukla              16
11/19/2012   Presented by: Neelesh Shukla   17

More Related Content

PPTX
Java exception handling
PPTX
Exceptionhandling
PPTX
Java Spring Framework
PDF
DNS hijacking using cloud providers – No verification needed
PPTX
OpenVAS
PPTX
Validation Controls in asp.net
PPTX
Exception handling c++
PPTX
Exception Handling in C#
Java exception handling
Exceptionhandling
Java Spring Framework
DNS hijacking using cloud providers – No verification needed
OpenVAS
Validation Controls in asp.net
Exception handling c++
Exception Handling in C#

What's hot (20)

PPTX
Understanding Cross-site Request Forgery
PPTX
Exception Handling in Java
PPTX
Exception handling in java
PPTX
Ppt on sql injection
PPTX
VB.NET:An introduction to Namespaces in .NET framework
PDF
Sql Injection - Vulnerability and Security
PPTX
Introduction to Web Application Penetration Testing
PPTX
SQL Injections - A Powerpoint Presentation
PPT
Java Networking
PPTX
ASP.NET Page Life Cycle
PPTX
Exception handling in ASP .NET
PPT
Dll injection
PPT
Object Oriented Concepts and Principles
PPTX
C# classes objects
PDF
Exception handling
PPTX
Templates in C++
PPT
Exception Handling in JAVA
PPTX
Exception Handling in Java
Understanding Cross-site Request Forgery
Exception Handling in Java
Exception handling in java
Ppt on sql injection
VB.NET:An introduction to Namespaces in .NET framework
Sql Injection - Vulnerability and Security
Introduction to Web Application Penetration Testing
SQL Injections - A Powerpoint Presentation
Java Networking
ASP.NET Page Life Cycle
Exception handling in ASP .NET
Dll injection
Object Oriented Concepts and Principles
C# classes objects
Exception handling
Templates in C++
Exception Handling in JAVA
Exception Handling in Java
Ad

Viewers also liked (20)

PPT
Exception handling
PPTX
Asp.NET Handlers and Modules
PPTX
Exception handling
PDF
C sharp chap5
PPTX
Debugging in .Net
PPT
Runnable interface.34
PPT
Java exception
PPT
Access Protection
PPTX
Effective Java - Chapter 4: Classes and Interfaces
PPTX
Exceptions in Java
PPT
Exception Handling Java
PPT
Exception Handling Mechanism in .NET CLR
PPTX
Java - Exception Handling
PPTX
Debugging
PDF
Java keywords
PPTX
CSharp Presentation
PDF
EVALUATION OF PROCESSES PARAMETER AND MECHANICAL PROPERTIES IN FRICTION STIR ...
PPTX
Error handling and debugging in vb
PPT
Packages in java
Exception handling
Asp.NET Handlers and Modules
Exception handling
C sharp chap5
Debugging in .Net
Runnable interface.34
Java exception
Access Protection
Effective Java - Chapter 4: Classes and Interfaces
Exceptions in Java
Exception Handling Java
Exception Handling Mechanism in .NET CLR
Java - Exception Handling
Debugging
Java keywords
CSharp Presentation
EVALUATION OF PROCESSES PARAMETER AND MECHANICAL PROPERTIES IN FRICTION STIR ...
Error handling and debugging in vb
Packages in java
Ad

Similar to Exception handling in asp.net (20)

PPTX
Exceptionhandelingin asp net
PDF
Java bad coding practices
PPTX
Chapter 5
PPT
Exception handling
PPT
Exception and ErrorHandling in Java .ppt
PDF
Perfomatix - Java Coding Standards
PPT
ASP.NET 05 - Exception Handling And Validation Controls
PDF
iOS Mobile App crash - Analysis
PPTX
Handling Exceptions and waits in selenium.pptx
PPTX
Exception handling with python class 12.pptx
PPT
Exception handling in asp.net
PDF
JAVA PPT -4 BY ADI.pdf
PPTX
C# Security Testing and Debugging
PPTX
Node.JS error handling best practices
PPTX
JAVA Presenttation topics Programs.pptx
PPTX
6-Error Handling.pptx
PPTX
Chapter_4_WP_with_C#_Exception_Handling_student_1.0.pptx
PPT
The Theory Of The Dom
PPTX
What is Exception Handling?
PPTX
Exception Hnadling java programming language
Exceptionhandelingin asp net
Java bad coding practices
Chapter 5
Exception handling
Exception and ErrorHandling in Java .ppt
Perfomatix - Java Coding Standards
ASP.NET 05 - Exception Handling And Validation Controls
iOS Mobile App crash - Analysis
Handling Exceptions and waits in selenium.pptx
Exception handling with python class 12.pptx
Exception handling in asp.net
JAVA PPT -4 BY ADI.pdf
C# Security Testing and Debugging
Node.JS error handling best practices
JAVA Presenttation topics Programs.pptx
6-Error Handling.pptx
Chapter_4_WP_with_C#_Exception_Handling_student_1.0.pptx
The Theory Of The Dom
What is Exception Handling?
Exception Hnadling java programming language

Recently uploaded (20)

PDF
Warning Signs of an Abusive Relationship
PPTX
Redesigned_Presentation_Pakistan_Heritage.pptx
DOCX
Free Pomodoro Tecnique Effect Guide -25mint - pomodorotimer.com.au
PPTX
Expert Custom Tailoring Services for All Needs.pptx
PPTX
Ethical_Clothing_Presentation for everyone
PDF
PrayerPetals- Empowering Women Through Faith-Based Support.pdf
PDF
The Safest Countries for Women in 2025 Where Rights, Respect, and Security Align
PDF
Pink Lined Illustration Communication Training Talking Presentation_20250804_...
PDF
Renovating a Midwest Ranch Rustic Modern Charm with Carved Doors
PDF
12 Reasons Why Women Stay In Abusive Relationships
PPTX
Hyperlipidemia current medication with lifestyle.
PDF
8 Effective Mosquito Control Tips for Gardens in the Monsoon Season
PDF
Exact Print’s T Shirt Printing Amplify Dynamic Shine
PPTX
Urbanization, definition, what is it and causes
PDF
12 Step-by-Step Methods to Clean Every Corner of Your Fridge
PDF
Student Housing Security From Metal Keys to Smart Access.pdf
DOC
学历学位硕士ACAP毕业证,澳大利亚凯斯林大学毕业证留学未毕业
PDF
Special Needs Dogs – How to Care for Them with Love .pdf
PPTX
Berlin+PowerPoint+Morph+Animation+Template+Black+variant.pptx
PDF
Maslow's Hierarchy Isn't a Ladder — It's a Loop (by Meenakshi Khakat)
Warning Signs of an Abusive Relationship
Redesigned_Presentation_Pakistan_Heritage.pptx
Free Pomodoro Tecnique Effect Guide -25mint - pomodorotimer.com.au
Expert Custom Tailoring Services for All Needs.pptx
Ethical_Clothing_Presentation for everyone
PrayerPetals- Empowering Women Through Faith-Based Support.pdf
The Safest Countries for Women in 2025 Where Rights, Respect, and Security Align
Pink Lined Illustration Communication Training Talking Presentation_20250804_...
Renovating a Midwest Ranch Rustic Modern Charm with Carved Doors
12 Reasons Why Women Stay In Abusive Relationships
Hyperlipidemia current medication with lifestyle.
8 Effective Mosquito Control Tips for Gardens in the Monsoon Season
Exact Print’s T Shirt Printing Amplify Dynamic Shine
Urbanization, definition, what is it and causes
12 Step-by-Step Methods to Clean Every Corner of Your Fridge
Student Housing Security From Metal Keys to Smart Access.pdf
学历学位硕士ACAP毕业证,澳大利亚凯斯林大学毕业证留学未毕业
Special Needs Dogs – How to Care for Them with Love .pdf
Berlin+PowerPoint+Morph+Animation+Template+Black+variant.pptx
Maslow's Hierarchy Isn't a Ladder — It's a Loop (by Meenakshi Khakat)

Exception handling in asp.net

  • 1. •Error occurred in execution time •Abnormal termination of program • Wrong execution result 11/19/2012 Presented by: Neelesh Shukla 1
  • 2. Is it a best practice to handle every error?  No, it is not best practice to handle every error. It degrades the performance.  You should use Error Handling in any of following situation otherwise try to avoid it. 1. If you can able to recover error in the catch block 2. To write clean-up code that must execute even if an exception occur 3. To record the exception in event log or sending email. 11/19/2012 Presented by: Neelesh Shukla 2
  • 3. Exception Handling  There are three ways to handle exceptions/errors in ASP.NET  1) Try-Catch block. This is also called Structured Exception Handling (SEH).  2) Error Events. They are page level or application level error events.  3) Custom Error Page. This is used for any unhandled error. 11/19/2012 Presented by: Neelesh Shukla 3
  • 4. 1) What is try Block?  Try Block consist of code that might generate error.  Try Block must be associated with one or more catch block or by finally block.  Try Block need not necessarily have a catch Block associated with it but in that case it must have a finally Block associate with it. 11/19/2012 Presented by: Neelesh Shukla 4
  • 5. What is catch Block?  Catch Block is used to recover from error generated in try Block.  In case of multiple catch Block, only the first matching catch Block is executed.  When you write multiple catch block you need to arrange them from specific exception type to more generic type.  When no matching catch block are able to handle exception, the default behavior of web page is to terminate the processing of the web page. 11/19/2012 Presented by: Neelesh Shukla 5
  • 6. What is finally Block?  Finally Block contains the code that always executes, whether or not any exception occurs.  When to use finally Block? - You should use finally block to write cleanup code. i.e. you can write code to close files, database connections, etc.  Only One finally block is associated with try block.  Finally block must appear after all the catch block.  If there is a transfer control statement such as goto, break or continue in either try or catch block the transfer happens only after the code in the finally block is executed.  If you use transfer control statement in finally block, you will receive compile time error. 11/19/2012 Presented by: Neelesh Shukla 6
  • 7. Example of Try-Catch-Finally Try { -------- -------- -------- } Catch(Exception ex) { ------- ------- } Finally { ---- } 11/19/2012 Presented by: Neelesh Shukla 7
  • 8. System-Defined Exception  DivideByZero Exception  NullReference Exception  IndexOutOfRange Exception  ArrayTypeMismatch Exception  Arithmetic Exception  Exception etc. 11/19/2012 Presented by: Neelesh Shukla 8
  • 9. Exception class object properties  Message: Get the error message.  Source: Set or get the name of the application or object that causes the exception.  StackTrace: Get a string representation of the frame on call stack at the time of current exception thrown.  TargetSite: Get the current method that throws exception.  InnerException: Get the system.exception instance that causes the current exception. 11/19/2012 Presented by: Neelesh Shukla 9
  • 10. In general, you will not be able to plan for, catch and recover from every possible exception that could occur within a page. ASP.NET helps by offering two techniques to handle page-level errors :  Error Events  Custom Error Page. 11/19/2012 Presented by: Neelesh Shukla 10
  • 11. 2)Error Events They are page level or application level error events:-  Page_Error()  Application_Error() 11/19/2012 Presented by: Neelesh Shukla 11
  • 12. Page_Error() private void Page_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); Response.Write("<h1>An error has occurred</h1>"); Response.Write("<h2>" + ex.Message + "</h2>"); Response.Write("<pre>" + ex.StackTrace + "</pre>"); Context.ClearError(); } Note: This event fire if the page control is not disposed. 11/19/2012 Presented by: Neelesh Shukla 12
  • 13. Application_Error()  The Error event of the Application class is fired when an exception is left unhandled. The handler is usually found in Global.asax void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs System.Exception ex = Context.Server.GetLastError(); ExceptionLog.MessageDetails(ex); // Code for handling error on Application level Response.Write("Handled error from Application <br>"); Server.ClearError(); } Note: In the code above that ClearError() method should always be called after the exception has been handled. If the ClearError() has not been cleared, the exception will still show up on the client's browser. 11/19/2012 Presented by: Neelesh Shukla 13
  • 14. 3) Custom Error Page  First change the Application_Error method to the following: protected void Application_Error(object sender, EventArgs e) { System.Exception ex = Context.Server.GetLastError(); ExceptionLog.MessageDetails(ex); }  Notice that I have removed the Server.ClearError();  Then add a customErrors section to your web.config file. This should be nested within the system.web element  Add a new custom error page “Error.aspx” into your project to display a custom Error page, if any unhandled error occurs. 11/19/2012 Presented by: Neelesh Shukla 14
  • 15. <system.web> ..... <customErrors mode="On" defaultRedirect="Error.aspx"> //<error statusCode="404" redirect="Error404.aspx" /> </customErrors> </system.web> Note: Details of status code can be found at http://httpstatus.es  To customize the default error page, one will have to change the default configuration settings of the application. There are three error modes in which an ASP.Net application can work: 1. Off Mode 2. On Mode 3. RemoteOnly Mode 11/19/2012 Presented by: Neelesh Shukla 15
  • 16. 1. When the error attribute is set to "Off", ASP.Net uses its default error page for both local and remote users in case of an error. 2. In case of "On" Mode, ASP.Net uses user-defined custom error page instead of its default error page for both local and remote users. If a custom error page is not specified, ASP.Net shows the error page describing how to enable remote viewing of errors. 3. The Error mode attribute determines whether or not an ASP.Net error message is displayed. By default, the mode value is set to "RemoteOnly". 11/19/2012 Presented by: Neelesh Shukla 16
  • 17. 11/19/2012 Presented by: Neelesh Shukla 17