• Common Errors• What are Exceptions• Exception Class• The Exception Chain• Catching Specific Exceptions• Nested Exception...
•   Programming mistakes•   Invalid Data•   Unexpected Circumstances•   Or even hardware failurePossible Solutions:•   Pro...
• Error due to unforeseen circumstances.• Can be caught in the code and handled• Critical ones can be reported in the form...
Every exception class derives from the base classSystem.Exception.The .NET Framework is full of predefined exceptionclasse...
Example :FileNotFoundException led to a NullReferenceException,which led to a custom UpdateFailedException.Using an except...
try{// Risky code goes here (opening a file, connecting to adatabase, and so on).}catch{// An error has been detected. You...
Exception blocks work a little like conditional code. As soon as a matchingexception handler is found, the appropriate cat...
Use the Help index in the class library referenceJust type in the class name, followed by aperiod, followed by the method ...
When an exception is thrown, .NET tries to find amatching catch statement in the current method.If the code isn’t in a loc...
protected void Page_Load(Object sender, EventArgs e){    try    {    DivideNumbers(5, 0);    }    catch (DivideByZeroExcep...
All you need to do is create an instance of the appropriateexception class and then use the throw statement.DivideByZeroEx...
You can create your own custom exception class.Custom exception classes should always inherit fromSystem.ApplicationExcept...
In many cases, it’s best not only to detect and catchexceptions but to log them as well.One of the most fail-safe logging ...
To view the Windows event logs, you use the Event Viewer tool that’sincluded with Windows.To launch it, begin by selecting...
catch (Exception err){lblResult.Text = "<b>Message:</b> " + err.Message + "<br /><br />";lblResult.Text += "<b>Source:</b>...
// Register the event source if needed.if (!EventLog.SourceExists("ProseTech")){// This registers the event source and cre...
Chapter 7
Chapter 7
Upcoming SlideShare
Loading in …5
×

Chapter 7

298 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
298
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Chapter 7

  1. 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. 2. • Programming mistakes• Invalid Data• Unexpected Circumstances• Or even hardware failurePossible Solutions:• Programming Defensively• Testing assumptions• Logging problems• Writing error handling code
  3. 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. 4. Every exception class derives from the base classSystem.Exception.The .NET Framework is full of predefined exceptionclasses:NullReferenceException, IOException, SqlException,DivideByZeroException, ArithmeticException,IOException, SecurityException, andmany moreDebug ➤ Exceptions ➤ Expand the CommonLanguage Runtime Exceptions group
  5. 5. Example :FileNotFoundException led to a NullReferenceException,which led to a custom UpdateFailedException.Using an exception handling block, the application can catchthe UpdateFailedException. It can then get more informationabout the source of the problem by following theInnerException property to the NullReferenceException,which in turn references the original FileNotFoundException.
  6. 6. try{// Risky code goes here (opening a file, connecting to adatabase, 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 anerror.}
  7. 7. Exception blocks work a little like conditional code. As soon as a matchingexception 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. }
  8. 8. Use the Help index in the class library referenceJust type in the class name, followed by aperiod, followed by the method name to jump to aspecific methodOnce you find the right method, scroll through themethod documentation until you find a section namedExceptions. This section lists all the possible exceptionsthat this method can throw.
  9. 9. When an exception is thrown, .NET tries to find amatching catch statement in the current method.If the code isn’t in a local structured exception blockor if none of the catch statements matches theexception, .NET will move up the call stack one levelat a time, searching for active exception handlers.Which means the problem will be caught furtherupstream in the calling code.
  10. 10. protected void Page_Load(Object sender, EventArgs e){ try { DivideNumbers(5, 0); } catch (DivideByZeroException err) { // Report error here. }}private decimal DivideNumbers(decimal number, decimaldivisor){return number/divisor;}
  11. 11. All you need to do is create an instance of the appropriateexception class and then use the throw statement.DivideByZeroException err = new DivideByZeroException();throw err;Alternatively, you can specify a custom error message byusing a different constructor:DivideByZeroException err = new DivideByZeroException("You supplied 0 for the divisor parameter. ");throw err;
  12. 12. You can create your own custom exception class.Custom exception classes should always inherit fromSystem.ApplicationException, which itself derives from the baseException 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;
  13. 13. In many cases, it’s best not only to detect and catchexceptions but to log them as well.One of the most fail-safe logging tools is the Windowsevent logging system, which is built into the Windowsoperating system and available to any application.Using the Windows event logs, your website can write textmessages that record errors or unusual events.The Windows event logs store your messages as well asvarious other details, such as the message type(information, error, and so on) and the time the messagewas left.
  14. 14. To view the Windows event logs, you use the Event Viewer tool that’sincluded with Windows.To launch it, begin by selecting Start ➤ Control Panel. Open theAdministrative Tools group, and then choose Event Viewer.Under the Windows Logs section, you’ll see the four logs that are
  15. 15. 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);}
  16. 16. // 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 doesnt exist,// it will be created automatically.EventLog log = new EventLog("ProseTech");log.Source = "DivideByZeroApp";log.WriteEntry(err.Message, EventLogEntryType.Error);

×