asp.net programming with c# and sql server first edition chapter 6 debugging and error handling

56
ASP.NET Programming with C# and SQL Server First Edition Chapter 6 Debugging and Error Handling

Upload: john-atkins

Post on 27-Dec-2015

228 views

Category:

Documents


0 download

TRANSCRIPT

ASP.NET Programming with C# and SQL Server

First Edition

Chapter 6Debugging and Error Handling

Objectives

In this chapter, you will:

• Study debugging concepts

• Use basic debugging techniques

• Trace errors with the Visual Studio Debugger

• Handle exceptions and errors

ASP.NET Programming with C# and SQL Server, First Edition 2

Introduction

• Regardless of experience, all programmers incorporate errors in programs at one time or another

• It is therefore essential to master the art of debugging

ASP.NET Programming with C# and SQL Server, First Edition 3

Introduction to Debugging

• Syntax: rules of a programming language

• Logic: the order in which parts of a program run

• Bug: an error in a program that causes it to function incorrectly

• Three types of errors:– Syntax errors– Logic errors– Run-time errors

• Debugging: the act of tracing and resolving errors in a program

ASP.NET Programming with C# and SQL Server, First Edition 4

Understanding Syntax Errors

• Syntax errors: occur when the statements are not recognized by the Visual Studio IDE– Can be caused by incorrect usage of C# code or

references to objects, methods, and variables that do not exist

• Most syntax errors are caused by incorrectly spelled or mistyped words

ASP.NET Programming with C# and SQL Server, First Edition 5

Interpreting Error and Warning Messages

• Error List window: displays two types of messages– Compiler error messages– Warning messages

• Compiler error messages: occur for any syntax errors– Specify the incorrect line of code

• Logic errors do not generate compiler errors

ASP.NET Programming with C# and SQL Server, First Edition 6

Interpreting Error and Warning Messages (cont’d.)

ASP.NET Programming with C# and SQL Server, First Edition 7

Figure 6-2 Compiler error message for a statement that does not end with a semicolon

Interpreting Error and Warning Messages (cont’d.)

• WarningLevel attribute: a page directive attribute specifying the types of warnings to report during compilation– Can be assigned values of 0 through 4– Higher values generate more warnings– 0 disables warnings entirely

• Changing the WarningLevel attribute does not prevent warnings from occurring– Only determines whether ASP.NET will report them

during compilation

ASP.NET Programming with C# and SQL Server, First Edition 8

Interpreting Error and Warning Messages (cont’d.)

ASP.NET Programming with C# and SQL Server, First Edition 9

Figure 6-3 Build error messages in the Move Estimator program

Handling Run-Time Errors• Run-time error: an error that occurs while a

program is executing– Does not necessarily represent C# language errors– Occurs when the program encounters code it cannot

execute

• Common run-time errors involve numeric calculations, such as divide by 0

• Different numeric data types behave differently when dividing by 0– Floating-point data types are assigned a value of

“infinity”– Integer data types display an error

ASP.NET Programming with C# and SQL Server, First Edition 10

ASP.NET Programming with C# and SQL Server, First Edition 11

Figure 6-4 Divide-by-zero error

Identifying Logic Errors

• Logic errors: flaws in a program’s design that prevent the program from producing correct results– Logic refers to the execution of program statements

in the correct order to produce the desired results

• Examples of logic errors:– Performing statements in the wrong order– Using the wrong arithmetic operator– Creation of an infinite loop

ASP.NET Programming with C# and SQL Server, First Edition 12

Using Basic Debugging Techniques

• Most advanced programming languages provide advanced features for debugging code

• First learn basic debugging techniques, and then learn the advanced features

• The best weapon against bugs is to write good code!

ASP.NET Programming with C# and SQL Server, First Edition 13

Writing Good Code

• The first and most important step in creating bug-free programs is to write good code– More discipline = fewer bugs

• Use good syntax

• Syntax errors may be difficult to pinpoint if you have a deeply nested set of control structures

ASP.NET Programming with C# and SQL Server, First Edition 14

Enabling Debugging

• By default, ASP.NET displays a generic error message that includes only a description and exception details about run-time errors

• Set Debug=“true” in the @Page directive to print detailed information about errors in the browser window

ASP.NET Programming with C# and SQL Server, First Edition 15

ASP.NET Programming with C# and SQL Server, First Edition 16

Figure 6-5 Detailed debugging information about a divide-by-zero error

Enabling Debugging (cont’d.)

• Use the ASP.NET Web Site Server Administration Tool to enable debugging for all pages in the project

• Click the Application Configuration link, and then the Configure Debugging and Tracing link, and then the Enable debugging box

• Note that the page directive overrides the application-level debugging setting

• Can manually start the application without debugging if desired

ASP.NET Programming with C# and SQL Server, First Edition 17

Tracing Errors with Response.Write() Statements

• Can manually trace your code by including Response.Write() statements at different points in the program– Display contents of a variable, array, or function

return value– Can monitor values as they change during execution

• Be sure to remove Response.Write() statements used for debug before deploying the application

• Driver program: a simplified, temporary program used for testing functions and other code

ASP.NET Programming with C# and SQL Server, First Edition 18

Tracing Errors with Response.Write() Statements

(cont’d.)

• Stub function: an empty function that serves as a placeholder for a program’s actual function– Typically returns a hard-coded value that represents

the result of the actual function– Allows you to check for errors in the program from

the ground up by isolating each function until it is correct

ASP.NET Programming with C# and SQL Server, First Edition 19

Using Comments to Locate Bugs

• Can comment out problematic lines by transforming them into comments– Helps to isolate where the problem is occurring– Restores lines incrementally to see where the

problem is occurring

ASP.NET Programming with C# and SQL Server, First Edition 20

Combining Debugging Techniques

• It can be helpful to combine debugging techniques when searching for errors– Use Response.Write() to monitor values– Comment out problematic code– Use stubs for functions that may have problems to

test the other parts of the program

ASP.NET Programming with C# and SQL Server, First Edition 21

Checking XHTML Elements

• If you cannot locate a bug using debugging methods, the error may be in the XHTML elements

• Must perform a line-by-line analysis of the XHTML code

• Ensure that:– All tags have opening and closing brackets– All necessary opening and closing tag pairs are

included

• Look at the IDE’s Error List window for validation errors

ASP.NET Programming with C# and SQL Server, First Edition 22

Analyzing Logic

• Code errors stemming from logic problems may be difficult to spot using tracing techniques

• Must analyze each statement on a case-by-case basis

• With logic errors, the code is syntactically correct but does not function as expected

ASP.NET Programming with C# and SQL Server, First Edition 23

Viewing Diagnostic Trace Information• Tracing: the examination of individual statements

in an executing program

• Set Trace=“true” in the @Page directive to view diagnostic trace information– Prints details of the page’s execution in the browser

• Diagnostic trace information can be stored in a log by enabling application-level tracing

• Use Web Site Administration Tool– Click Application Configuration link, and then

Configure debugging and tracing link, and then Capture tracing information box

ASP.NET Programming with C# and SQL Server, First Edition 24

ASP.NET Programming with C# and SQL Server, First Edition 25

Figure 6-7 Diagnostic trace output

Viewing Diagnostic Trace Information (cont’d.)

• After enabling application-level tracing, you can view the trace log using Trace Viewer

• Open the Trace.axd file in your project’s root folder– It contains links to the trace details

• Trace info shows request information such as events and object collection variables– Does not show code details

• Trace.Write() and Trace.Warn() methods of the TraceContext class can be used to add custom messages to the trace diagnostic output

ASP.NET Programming with C# and SQL Server, First Edition 26

ASP.NET Programming with C# and SQL Server, First Edition 27

Figure 6-8 Trace Viewer

Viewing Diagnostic Trace Information (cont’d.)

• Debugging code should only run if tracing is enabled– Use Trace.IsEnabled property to determine if

tracing is enabled

• Ensure that tracing is turned off for production environments

ASP.NET Programming with C# and SQL Server, First Edition 28

ASP.NET Programming with C# and SQL Server, First Edition 29

Figure 6-9 Custom trace message

Tracing Errors with the Visual Studio Debugger

• Basic debugging techniques are useful with smaller programs

• Finding errors in larger programs is difficult using error messages and manually checking your code

• Debugger: a tool in the Visual Studio IDE that contains options for tracing lines of code interactively

ASP.NET Programming with C# and SQL Server, First Edition 30

Stepping Through Your Code

• Use the Debug menu to start the debugger

• Step Into command: executes a single line of code and pauses

• Step Over command: treats a function call as a single line of code (does not step into the function)

• Breakpoint: a statement that switches program execution to break mode

• Break mode: a state in which the program execution is temporarily suspended, allowing you to monitor values and trace execution one command at a time

ASP.NET Programming with C# and SQL Server, First Edition 31

Stepping Through Your Code (cont’d.)

• Continue command: executes the rest of the program normally or until another breakpoint is encountered

• Stop Debugging command: ends a debugging session without executing the rest of the program

• Step Out command: executes all remaining code within the current function

• Run to Cursor command: program runs normally until it reaches the statement where your cursor is located, and then enters break mode

ASP.NET Programming with C# and SQL Server, First Edition 32

Stepping Through Your Code (cont’d.)

• When you enter break mode, the Locals and Watch windows appear at the bottom of the IDE

• To insert a breakpoint, click in the statement and select Toggle Breakpoint from the Debug menu– A red circle appears in the margin to identify the

breakpoint

• Changes made to code during break mode will not take effect while the program is executing

• Clear breakpoints individually using Toggle Breakpoint, or use Delete All Breakpoints in the Debug menu

ASP.NET Programming with C# and SQL Server, First Edition 33

Working with the Debugger Windows• Four debugging windows are available when in

break mode:– Locals– Watch– Immediate– Call Stack

• You can display these windows using the Debug menu – Windows submenu

• Locals window: displays all local variables within the currently running function and their values– Right-click the value, and select Edit Value to

change the value while the program is in break modeASP.NET Programming with C# and SQL Server, First Edition 34

ASP.NET Programming with C# and SQL Server, First Edition 35

Figure 6-10 Locals window in break mode

Working with the Debugger Windows (cont’d.)

• Watch window: monitors variables and expressions in break mode– Enter a variable or expression in the first column in an

empty row– Useful for determining when a variable changes value

• Immediate window: used to monitor specific variables and expressions in break mode– Enter the variable or expression in the window and

press Enter to see its current value– Enter a variable, and then equals, and then a value to

change the variable’s value during break mode

ASP.NET Programming with C# and SQL Server, First Edition 36

ASP.NET Programming with C# and SQL Server, First Edition 37

Figure 6-11 Variables in the Watch window

ASP.NET Programming with C# and SQL Server, First Edition 38

Figure 6-12 Variables in the Immediate window

Working with the Debugger Windows (cont’d.)

• Call Stack window: appears automatically when you enter break mode

• Call stack: refers to the order in which procedures (such as functions, methods, or event handlers) execute within a program– When a procedure is called, the procedure is added

to the top of the call stack– When a procedure ends, it is removed from the top

of the call stack

• Call stack window allows you to see the flow of the program within procedure calls

ASP.NET Programming with C# and SQL Server, First Edition 39

Handling Exceptions and Errors

• Your goal is to write code that anticipates problems and gracefully handles them

• Bulletproofing: writing code to anticipate and handle potential problems

• Exception handling: allows a program to handle problems as they occur during execution

• Exception: indicates that something unexpected occurred during program execution– May or may not be an error

• C# includes exception-handling capabilities

ASP.NET Programming with C# and SQL Server, First Edition 40

Handling Exceptions and Errors (cont’d.)

• Use exception handling to test any type of input or functionality that is external to the program

• Three levels at which you can handle exceptions:– Code level– Page level– Application level

• Always strive to handle exceptions at the code level with try…catch blocks

• If you cannot handle the error at the code level, handle it at the page level

ASP.NET Programming with C# and SQL Server, First Edition 41

Throwing Exceptions

• try statement: used to enclose code that might contain an exception

• Throwing an exception: the process by which a try statement generates an exception class object

• Syntax:

try {

statements;

}

ASP.NET Programming with C# and SQL Server, First Edition 42

Throwing Exceptions (cont’d.)

• In C#, exceptions are represented by classes based on the Exception class

• ArithmeticException class: thrown for errors in an arithmetic, casting, or conversion operation

• MissingMemberException: thrown when attempting to access a class method or property that does not exist

• throw statement: used to manually throw an exception and an Exception object

ASP.NET Programming with C# and SQL Server, First Edition 43

Catching Exceptions• Exception objects contain properties and methods

that describe what went wrong– Message property: contains a message describing

the current exception– ToString() method: returns a more detailed

description of the exception

• catch statement: used after an error is thrown to handle the exception object

• Syntax: catch(exception_type identifier) {

statements;

}ASP.NET Programming with C# and SQL Server, First Edition 44

Catching Exceptions (cont’d.)

• When a try statement throws an exception, the compiler executes the nearest catch statement that matches the exception type– If no match in the current try block, the compiler

checks for a matching catch statement in the next function or method in the call stack

– If no matches are found, the compiler relies on any existing page-level exception handling

– If no page-level exception handling, the compiler looks to application-level exception handling

– If none found, a default error message is displayed

ASP.NET Programming with C# and SQL Server, First Edition 45

Catching Exceptions (cont’d.)

• A try statement can contain more than one catch block– catch blocks are examined for a match of the

exception type in the order in which they appear in the try statement

– List the most specific exception types first, and then the more general types

• Exception class: used to catch any type of exception that is thrown

ASP.NET Programming with C# and SQL Server, First Edition 46

Executing Final Exception-Handling Tasks

• finally statement: executes regardless of whether the associated try block throws an exception– Used to perform clean-up tasks

• If there is no catch statement, the finally statement executes before the compiler begins searching for a higher-level catch statement

ASP.NET Programming with C# and SQL Server, First Edition 47

Handling Page-Level Errors

• Most basic page-level error handling is to assign an error page to the ErrorPage attribute of the @Page directive

• To programmatically control page-level error-handling, you must create an event handler

• Use the System.EventHandler() function in the Page_Load() event handler to designate a function as the error event handler

• To redirect the browser to an error page from the error event handler, use System.Transfer() method

ASP.NET Programming with C# and SQL Server, First Edition 48

Handling Page-Level Errors (cont’d.)

• Must clear an error after handling it with Server.ClearError() method

• To pass an error to a page error event handler, you must throw it from the code level

ASP.NET Programming with C# and SQL Server, First Edition 49

Handling Application-Level Errors

• Use the System.Transfer() method to redirect the browser to a generic error page

• Use the Server.Clear() method to clear errors

• Use the Server.GetLastError() method to access the last exception that occurred

• Application errors are handed in the Global.asax file– Use Website menu – Add New Item to add a Global.asax file

• Application_Error(): an event handler created by default in the Global.asax file

ASP.NET Programming with C# and SQL Server, First Edition 50

ASP.NET Programming with C# and SQL Server, First Edition 51

Figure 6-13 Global.asax file

Summary

• All programming languages have their own syntax

• Logic refers to the order in which parts of a program are executed

• A bug is an error that causes the program to function incorrectly

• Syntax errors occur when the interpreter fails to recognize code

• Compiler error messages occur for syntax errors

• Run-time errors occur while a program is running

• Logic errors are flaws in the program’s design

ASP.NET Programming with C# and SQL Server, First Edition 52

Summary (cont’d.)

• Use Debug attribute in the @Page directive to print detailed information about errors

• Use Response.Write() statements to display contents of variables when debugging

• Stub functions are empty functions that serve as placeholders

• Perform a line-by-line analysis of your XHTML code to look for errors

• Analyze statements on a case-by-case basis to identify logic errors

ASP.NET Programming with C# and SQL Server, First Edition 53

Summary (cont’d.)

• Tracing is the examination of individual statements in an executing program

• Use the Trace attribute of the @Page directive to view diagnostic trace information

• Use Trace Viewer to view application-level trace information

• Debugger is a program to help trace each line of code

• Break mode is the temporary suspension of program execution

ASP.NET Programming with C# and SQL Server, First Edition 54

Summary (cont’d.)

• Breakpoint is a statement at which program execution enters break mode

• Step Into, Step Over, and Step Out commands are used in break mode to debug a program

• Locals and Watch windows allow you to monitor variables and expressions in break mode

• Call stack refers to the order in which procedures execute in a program

• Exception handling allows programs to handle errors as they occur during execution

ASP.NET Programming with C# and SQL Server, First Edition 55

Summary (cont’d.)

• Use the ErrorPage attribute of the @Page directive to handle page-level errors

• Create a page error event handler to programmatically control page-level error handling

• Application errors are handled in the Global.asax file

ASP.NET Programming with C# and SQL Server, First Edition 56