SlideShare a Scribd company logo
1 of 18
• Common Errors
• What are Exceptions
• Exception Class
• The Exception Chain
• Catching Specific Exceptions
• Nested Exception Handlers
• Throwing your own Exceptions
• Logging Exceptions
• Windows Event Logs
• Writing to the Event Log
• Retrieving Log Information
•   Programming mistakes
•   Invalid Data
•   Unexpected Circumstances
•   Or even hardware failure

Possible Solutions:

•   Programming Defensively
•   Testing assumptions
•   Logging problems
•   Writing error handling code
• Error due to unforeseen circumstances.
• Can be caught in the code and handled
• Critical ones can be reported in the form of user
  friendly page of information


• Exceptions are object-based
• Exceptions are caught based on their type
• Exception handlers use a modern block structure
• Exception handlers are multilayered
• Exceptions are a generic part of the .NET Framework
Every exception class derives from the base class
System.Exception.

The .NET Framework is full of predefined exception
classes:

NullReferenceException, IOException, SqlException,
DivideByZeroException, ArithmeticException,
IOException, SecurityException, andmany more


Debug ➤ Exceptions ➤ Expand the Common
Language Runtime Exceptions group
Example :

FileNotFoundException led to a NullReferenceException,
which led to a custom UpdateFailedException.

Using an exception handling block, the application can catch
the UpdateFailedException. It can then get more information
about the source of the problem by following the
InnerException property to the NullReferenceException,
which in turn references the original FileNotFoundException.
try
{
// Risky code goes here (opening a file, connecting to a
database, and so on).
}
catch
{
// An error has been detected. You can deal with it here.
}
finally
{
// Time to clean up, regardless of whether or not there was an
error.
}
Exception blocks work a little like conditional code. As soon as a matching
exception handler is found, the appropriate catch code is invoked.

                try
                {
                // Risky database code goes here.
                }
                catch (System.Data.SqlClient.SqlException
                err)
                {
                // Catches common problems like connection errors.
                }
                catch (System.NullReferenceException err)
                {
                // Catches problems resulting from an uninitialized object.
                }
                catch (System.Exception err)
                {
                // Catches any other errors.
                }
Use the Help index in the class library reference

Just type in the class name, followed by a
period, followed by the method name to jump to a
specific method

Once you find the right method, scroll through the
method documentation until you find a section named
Exceptions. This section lists all the possible exceptions
that this method can throw.
When an exception is thrown, .NET tries to find a
matching catch statement in the current method.

If the code isn’t in a local structured exception block
or if none of the catch statements matches the
exception, .NET will move up the call stack one level
at a time, searching for active exception handlers.

Which means the problem will be caught further
upstream in the calling code.
protected void Page_Load(Object sender, EventArgs e)
{
    try
    {
    DivideNumbers(5, 0);
    }
    catch (DivideByZeroException err)
    {
    // Report error here.
    }
}

private decimal DivideNumbers(decimal number, decimal
divisor)
{
return number/divisor;
}
All you need to do is create an instance of the appropriate
exception class and then use the throw statement.

DivideByZeroException err = new DivideByZeroException();
throw err;

Alternatively, you can specify a custom error message by
using a different constructor:

DivideByZeroException err = new DivideByZeroException(
"You supplied 0 for the divisor parameter. ");
throw err;
You can create your own custom exception class.
Custom exception classes should always inherit from
System.ApplicationException, which itself derives from the base
Exception class.

public class CustomDivideByZeroException : ApplicationException
{
// Add a variable to specify the "other" number.
// This might help diagnose the problem.
public decimal DividingNumber;
}

CustomDivideByZeroException err = new CustomDivideByZeroException();
err.DividingNumber = number;
throw err;
In many cases, it’s best not only to detect and catch
exceptions but to log them as well.

One of the most fail-safe logging tools is the Windows
event logging system, which is built into the Windows
operating system and available to any application.

Using the Windows event logs, your website can write text
messages that record errors or unusual events.

The Windows event logs store your messages as well as
various other details, such as the message type
(information, error, and so on) and the time the message
was left.
To view the Windows event logs, you use the Event Viewer tool that’s
included with Windows.

To launch it, begin by selecting Start ➤ Control Panel. Open the
Administrative Tools group, and then choose Event Viewer.

Under the Windows Logs section, you’ll see the four logs that are
catch (Exception err)
{
lblResult.Text = "<b>Message:</b> " + err.Message + "<br /><br />";
lblResult.Text += "<b>Source:</b> " + err.Source + "<br /><br />";
lblResult.Text += "<b>Stack Trace:</b> " + err.StackTrace;
lblResult.ForeColor = System.Drawing.Color.Red;

// Write the information to the event log.
EventLog log = new EventLog();
log.Source = "DivisionPage";
log.WriteEntry(err.Message, EventLogEntryType.Error);
}
// Register the event source if needed.
if (!EventLog.SourceExists("ProseTech"))
{
// This registers the event source and creates the custom log,
// if needed.
EventLog.CreateEventSource("DivideByZeroApp", "ProseTech");
}
// Open the log. If the log doesn't exist,
// it will be created automatically.
EventLog log = new EventLog("ProseTech");
log.Source = "DivideByZeroApp";
log.WriteEntry(err.Message, EventLogEntryType.Error);
Chapter 7

More Related Content

What's hot

Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling ConceptsVicter Paul
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaARAFAT ISLAM
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statementmyrajendra
 
Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .NetMindfire Solutions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 

What's hot (19)

Exception handling
Exception handling Exception handling
Exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java review: try catch
Java review: try catchJava review: try catch
Java review: try catch
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .Net
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 

Similar to Chapter 7

Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling pptJavabynataraJ
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1Shinu Suresh
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Exceptions
ExceptionsExceptions
Exceptionsmotthu18
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 
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 ControlsRandy Connolly
 

Similar to Chapter 7 (20)

Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception
ExceptionException
Exception
 
Exception handling
Exception handlingException handling
Exception handling
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exceptions
ExceptionsExceptions
Exceptions
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Exceptions
ExceptionsExceptions
Exceptions
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .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
 

More from application developer (20)

Chapter 26
Chapter 26Chapter 26
Chapter 26
 
Chapter 25
Chapter 25Chapter 25
Chapter 25
 
Chapter 23
Chapter 23Chapter 23
Chapter 23
 
Assignment
AssignmentAssignment
Assignment
 
Next step job board (Assignment)
Next step job board (Assignment)Next step job board (Assignment)
Next step job board (Assignment)
 
Chapter 19
Chapter 19Chapter 19
Chapter 19
 
Chapter 18
Chapter 18Chapter 18
Chapter 18
 
Chapter 17
Chapter 17Chapter 17
Chapter 17
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
 
Week 3 assignment
Week 3 assignmentWeek 3 assignment
Week 3 assignment
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Chapter 13
Chapter 13Chapter 13
Chapter 13
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
Chapter 10
Chapter 10Chapter 10
Chapter 10
 
C # test paper
C # test paperC # test paper
C # test paper
 
Chapter 9
Chapter 9Chapter 9
Chapter 9
 
Chapter 8 part2
Chapter 8   part2Chapter 8   part2
Chapter 8 part2
 
Chapter 8 part1
Chapter 8   part1Chapter 8   part1
Chapter 8 part1
 

Recently uploaded

Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 

Recently uploaded (20)

Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 

Chapter 7

  • 1. • Common Errors • What are Exceptions • Exception Class • The Exception Chain • Catching Specific Exceptions • Nested Exception Handlers • Throwing your own Exceptions • Logging Exceptions • Windows Event Logs • Writing to the Event Log • Retrieving Log Information
  • 2. Programming mistakes • Invalid Data • Unexpected Circumstances • Or even hardware failure Possible Solutions: • Programming Defensively • Testing assumptions • Logging problems • Writing error handling code
  • 3. • Error due to unforeseen circumstances. • Can be caught in the code and handled • Critical ones can be reported in the form of user friendly page of information • Exceptions are object-based • Exceptions are caught based on their type • Exception handlers use a modern block structure • Exception handlers are multilayered • Exceptions are a generic part of the .NET Framework
  • 4. Every exception class derives from the base class System.Exception. The .NET Framework is full of predefined exception classes: NullReferenceException, IOException, SqlException, DivideByZeroException, ArithmeticException, IOException, SecurityException, andmany more Debug ➤ Exceptions ➤ Expand the Common Language Runtime Exceptions group
  • 5.
  • 6. Example : FileNotFoundException led to a NullReferenceException, which led to a custom UpdateFailedException. Using an exception handling block, the application can catch the UpdateFailedException. It can then get more information about the source of the problem by following the InnerException property to the NullReferenceException, which in turn references the original FileNotFoundException.
  • 7. try { // Risky code goes here (opening a file, connecting to a database, and so on). } catch { // An error has been detected. You can deal with it here. } finally { // Time to clean up, regardless of whether or not there was an error. }
  • 8. Exception blocks work a little like conditional code. As soon as a matching exception handler is found, the appropriate catch code is invoked. try { // Risky database code goes here. } catch (System.Data.SqlClient.SqlException err) { // Catches common problems like connection errors. } catch (System.NullReferenceException err) { // Catches problems resulting from an uninitialized object. } catch (System.Exception err) { // Catches any other errors. }
  • 9. Use the Help index in the class library reference Just type in the class name, followed by a period, followed by the method name to jump to a specific method Once you find the right method, scroll through the method documentation until you find a section named Exceptions. This section lists all the possible exceptions that this method can throw.
  • 10. When an exception is thrown, .NET tries to find a matching catch statement in the current method. If the code isn’t in a local structured exception block or if none of the catch statements matches the exception, .NET will move up the call stack one level at a time, searching for active exception handlers. Which means the problem will be caught further upstream in the calling code.
  • 11. protected void Page_Load(Object sender, EventArgs e) { try { DivideNumbers(5, 0); } catch (DivideByZeroException err) { // Report error here. } } private decimal DivideNumbers(decimal number, decimal divisor) { return number/divisor; }
  • 12. All you need to do is create an instance of the appropriate exception class and then use the throw statement. DivideByZeroException err = new DivideByZeroException(); throw err; Alternatively, you can specify a custom error message by using a different constructor: DivideByZeroException err = new DivideByZeroException( "You supplied 0 for the divisor parameter. "); throw err;
  • 13. You can create your own custom exception class. Custom exception classes should always inherit from System.ApplicationException, which itself derives from the base Exception class. public class CustomDivideByZeroException : ApplicationException { // Add a variable to specify the "other" number. // This might help diagnose the problem. public decimal DividingNumber; } CustomDivideByZeroException err = new CustomDivideByZeroException(); err.DividingNumber = number; throw err;
  • 14. In many cases, it’s best not only to detect and catch exceptions but to log them as well. One of the most fail-safe logging tools is the Windows event logging system, which is built into the Windows operating system and available to any application. Using the Windows event logs, your website can write text messages that record errors or unusual events. The Windows event logs store your messages as well as various other details, such as the message type (information, error, and so on) and the time the message was left.
  • 15. To view the Windows event logs, you use the Event Viewer tool that’s included with Windows. To launch it, begin by selecting Start ➤ Control Panel. Open the Administrative Tools group, and then choose Event Viewer. Under the Windows Logs section, you’ll see the four logs that are
  • 16. catch (Exception err) { lblResult.Text = "<b>Message:</b> " + err.Message + "<br /><br />"; lblResult.Text += "<b>Source:</b> " + err.Source + "<br /><br />"; lblResult.Text += "<b>Stack Trace:</b> " + err.StackTrace; lblResult.ForeColor = System.Drawing.Color.Red; // Write the information to the event log. EventLog log = new EventLog(); log.Source = "DivisionPage"; log.WriteEntry(err.Message, EventLogEntryType.Error); }
  • 17. // Register the event source if needed. if (!EventLog.SourceExists("ProseTech")) { // This registers the event source and creates the custom log, // if needed. EventLog.CreateEventSource("DivideByZeroApp", "ProseTech"); } // Open the log. If the log doesn't exist, // it will be created automatically. EventLog log = new EventLog("ProseTech"); log.Source = "DivideByZeroApp"; log.WriteEntry(err.Message, EventLogEntryType.Error);