+ All Categories
Home > Technology > Chapter 7

Chapter 7

Date post: 20-May-2015
Category:
Upload: application-developer
View: 181 times
Download: 1 times
Share this document with a friend
Popular Tags:
18
AGENDA 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
Transcript
Page 1: Chapter 7

AGENDA

• 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

Page 2: Chapter 7

Common Error Causes

• Programming mistakes• Invalid Data• Unexpected Circumstances• Or even hardware failure

Possible Solutions:

• Programming Defensively• Testing assumptions• Logging problems• Writing error handling code

Page 3: Chapter 7

Exception

• 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

Page 4: Chapter 7

System.Exception Class

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

Page 5: Chapter 7

• Exception Class

Page 6: Chapter 7

The Exception Chain

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.

Page 7: Chapter 7

Handling Exceptions

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.}

Page 8: Chapter 7

Catching Specific Exceptions

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.

}

Page 9: Chapter 7

Determining the Exceptions you need to catch

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.

Page 10: Chapter 7

Nested Exception Handlers

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.

Page 11: Chapter 7

Nested Exception Handlersprotected 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;}

Page 12: Chapter 7

Throwing Your Own Exceptions

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;

Page 13: Chapter 7

Creating Custom Exception classYou 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;

Page 14: Chapter 7

Logging Exceptions

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.

Page 15: Chapter 7

Viewing the Windows Event LogsTo 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

Page 16: Chapter 7

Writing to the Event Log

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);}

Page 17: Chapter 7

Custom Logs

// 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);

Page 18: Chapter 7

A Custom Logging Class


Recommended