SlideShare ist ein Scribd-Unternehmen logo
1 von 17
•Error occurred in execution time
•Abnormal termination of program
• Wrong execution result

2/4/2014

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.
2/4/2014

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.
2/4/2014

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.

2/4/2014

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.
2/4/2014

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.

2/4/2014

Presented by: Neelesh Shukla

6
Example of Try-Catch-Finally
Try
{
---------------------}
Catch(Exception ex)
{
------------}
Finally
{
---}
2/4/2014

Presented by: Neelesh Shukla

7
System-Defined Exception
 DivideByZero Exception
 NullReference Exception
 IndexOutOfRange Exception
 ArrayTypeMismatch Exception

 Arithmetic Exception
 Exception etc.

2/4/2014

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.
2/4/2014

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.

2/4/2014

Presented by: Neelesh Shukla

10
2)Error Events
They are page level or application level error events: Page_Error()
 Application_Error()

2/4/2014

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.
2/4/2014

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.
2/4/2014

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.

2/4/2014

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.
2.
3.

Off Mode
On Mode
RemoteOnly Mode
2/4/2014

Presented by: Neelesh Shukla

15
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".
1.

2/4/2014

Presented by: Neelesh Shukla

16
2/4/2014

Presented by: Neelesh Shukla

17

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (15)

Sql Injection Tutorial!
Sql Injection Tutorial!Sql Injection Tutorial!
Sql Injection Tutorial!
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best Practices
 
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoSQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
 
D:\Technical\Ppt\Sql Injection
D:\Technical\Ppt\Sql InjectionD:\Technical\Ppt\Sql Injection
D:\Technical\Ppt\Sql Injection
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
Web Hacking Series Part 4
Web Hacking Series Part 4Web Hacking Series Part 4
Web Hacking Series Part 4
 
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampDEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
 
Concurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and GotchasConcurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and Gotchas
 
Sql Injection attacks and prevention
Sql Injection attacks and preventionSql Injection attacks and prevention
Sql Injection attacks and prevention
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
 
Sql Injection Attacks Siddhesh
Sql Injection Attacks SiddheshSql Injection Attacks Siddhesh
Sql Injection Attacks Siddhesh
 
Sql injection
Sql injectionSql injection
Sql injection
 
SQL Injection
SQL Injection SQL Injection
SQL Injection
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Vulnerable Active Record: A tale of SQL Injection in PHP Framework
Vulnerable Active Record: A tale of SQL Injection in PHP FrameworkVulnerable Active Record: A tale of SQL Injection in PHP Framework
Vulnerable Active Record: A tale of SQL Injection in PHP Framework
 

Andere mochten auch

pengantar ilmu mudigah
pengantar ilmu mudigahpengantar ilmu mudigah
pengantar ilmu mudigah
Dirga Januar
 
Research on Afghan Legal Courts
Research on Afghan Legal CourtsResearch on Afghan Legal Courts
Research on Afghan Legal Courts
IDCOAFGHANISTAN
 
Laporan akhir tingkat prokrastinasi di kalangan mahasiswa(i) ilmu komputer
Laporan akhir tingkat prokrastinasi di kalangan mahasiswa(i) ilmu komputerLaporan akhir tingkat prokrastinasi di kalangan mahasiswa(i) ilmu komputer
Laporan akhir tingkat prokrastinasi di kalangan mahasiswa(i) ilmu komputer
Ridha_nra
 

Andere mochten auch (19)

Factfile pro forma
Factfile pro formaFactfile pro forma
Factfile pro forma
 
pengantar ilmu mudigah
pengantar ilmu mudigahpengantar ilmu mudigah
pengantar ilmu mudigah
 
Демография и антропотоки
Демография и антропотоки Демография и антропотоки
Демография и антропотоки
 
task 1
task 1task 1
task 1
 
Charfauros bus415 wk4. Copyright 2013 Edward F. T. Charfauros. Reference, www...
Charfauros bus415 wk4. Copyright 2013 Edward F. T. Charfauros. Reference, www...Charfauros bus415 wk4. Copyright 2013 Edward F. T. Charfauros. Reference, www...
Charfauros bus415 wk4. Copyright 2013 Edward F. T. Charfauros. Reference, www...
 
03 palvele asiakastasi digitaalisesti - jari jalonen - vintor
03 palvele asiakastasi digitaalisesti - jari jalonen - vintor03 palvele asiakastasi digitaalisesti - jari jalonen - vintor
03 palvele asiakastasi digitaalisesti - jari jalonen - vintor
 
Rétrospective 2015
Rétrospective 2015Rétrospective 2015
Rétrospective 2015
 
Language of Politics on Twitter - 02 Twitter
Language of Politics on Twitter - 02 TwitterLanguage of Politics on Twitter - 02 Twitter
Language of Politics on Twitter - 02 Twitter
 
Research on Afghan Legal Courts
Research on Afghan Legal CourtsResearch on Afghan Legal Courts
Research on Afghan Legal Courts
 
Ppt ro cdc 4
Ppt ro   cdc 4Ppt ro   cdc 4
Ppt ro cdc 4
 
Factfile pro forma
Factfile pro formaFactfile pro forma
Factfile pro forma
 
Онтологическое знание
Онтологическое знаниеОнтологическое знание
Онтологическое знание
 
Tic
TicTic
Tic
 
Focus notes
Focus notesFocus notes
Focus notes
 
learning enviroment : indoor area
learning enviroment : indoor arealearning enviroment : indoor area
learning enviroment : indoor area
 
RPJMD 2007 - 2011 kabupaten mappi
RPJMD 2007 - 2011 kabupaten mappiRPJMD 2007 - 2011 kabupaten mappi
RPJMD 2007 - 2011 kabupaten mappi
 
Anthony Chow - Challenge 1 - Virtual Design Master
Anthony Chow - Challenge 1 - Virtual Design MasterAnthony Chow - Challenge 1 - Virtual Design Master
Anthony Chow - Challenge 1 - Virtual Design Master
 
Byron Schaller - Challenge 3 - Virtual Design Master
Byron Schaller - Challenge 3 - Virtual Design MasterByron Schaller - Challenge 3 - Virtual Design Master
Byron Schaller - Challenge 3 - Virtual Design Master
 
Laporan akhir tingkat prokrastinasi di kalangan mahasiswa(i) ilmu komputer
Laporan akhir tingkat prokrastinasi di kalangan mahasiswa(i) ilmu komputerLaporan akhir tingkat prokrastinasi di kalangan mahasiswa(i) ilmu komputer
Laporan akhir tingkat prokrastinasi di kalangan mahasiswa(i) ilmu komputer
 

Ähnlich wie Exceptionhandelingin asp net

香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
yayao
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
myrajendra
 
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdfVISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
NALANDACSCCENTRE
 

Ähnlich wie Exceptionhandelingin asp net (20)

Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test
 
Exception handling
Exception handlingException handling
Exception handling
 
Java bad coding practices
Java bad coding practicesJava bad coding practices
Java bad coding practices
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
 
Role of .NET in Exception Handling
Role of .NET in Exception HandlingRole of .NET in Exception Handling
Role of .NET in Exception Handling
 
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable codenullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Exception
ExceptionException
Exception
 
6-Error Handling.pptx
6-Error Handling.pptx6-Error Handling.pptx
6-Error Handling.pptx
 
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdfVISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
 
jDriver Presentation
jDriver PresentationjDriver Presentation
jDriver Presentation
 
C# Security Testing and Debugging
C# Security Testing and DebuggingC# Security Testing and Debugging
C# Security Testing and Debugging
 
Introduction to php exception and error management
Introduction to php  exception and error managementIntroduction to php  exception and error management
Introduction to php exception and error management
 
Exception
ExceptionException
Exception
 

Kürzlich hochgeladen

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Kürzlich hochgeladen (20)

HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 

Exceptionhandelingin asp net

  • 1. •Error occurred in execution time •Abnormal termination of program • Wrong execution result 2/4/2014 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. 2/4/2014 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. 2/4/2014 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. 2/4/2014 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. 2/4/2014 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. 2/4/2014 Presented by: Neelesh Shukla 6
  • 7. Example of Try-Catch-Finally Try { ---------------------} Catch(Exception ex) { ------------} Finally { ---} 2/4/2014 Presented by: Neelesh Shukla 7
  • 8. System-Defined Exception  DivideByZero Exception  NullReference Exception  IndexOutOfRange Exception  ArrayTypeMismatch Exception  Arithmetic Exception  Exception etc. 2/4/2014 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. 2/4/2014 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. 2/4/2014 Presented by: Neelesh Shukla 10
  • 11. 2)Error Events They are page level or application level error events: Page_Error()  Application_Error() 2/4/2014 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. 2/4/2014 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. 2/4/2014 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. 2/4/2014 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. 2. 3. Off Mode On Mode RemoteOnly Mode 2/4/2014 Presented by: Neelesh Shukla 15
  • 16. 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". 1. 2/4/2014 Presented by: Neelesh Shukla 16