1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 7 pptx

90 281 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 90
Dung lượng 2,03 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Sources of ErrorsThe errors that occur in an ASP.NET page can be grouped into four categories: ❑ Parser errors: These occur because of incorrect syntax or bad grammar within the ASP.NET

Trang 2

The following code shows the syntax for using the ToString()method of the Convertclass:

SomeVariable = Convert.ToString(SomeInteger);

'Convert Integer to String

Try to Break Your Code

This can be a more difficult task than expected It is often difficult for the developer to anticipate all theunusual things a user might attempt to do with the application, such as accidentally typing in letterswhen numbers are required, or supplying an answer that was longer than anticipated, or even

deliberately trying to break it

So, when it is time to test your application, try to think like a user who isn't too computer literate Youcan break down your testing strategy into two main approaches:

Be nice to your program: Supply your program with legal values, or values that your program isdesigned to expect and handle For instance, if your program contains an age field, supply onlynumbers, not letters Watch how your program behaves – does it respond as you expect it towith the legal values supplied to it?

Try to break your program: This is the fun part Supply your program with illegal values Forinstance, provide string values where integers are expected This ensures that your programhandles all illegal values appropriately Depending on the kind of data you are expecting inyour program, you could to do anything from a simple numeric or alphabetic check to a validitycheck (such as inserting invalid dates into a date field) If your program spans several pages,then surf to some of the pages out of the expected sequence

Both these techniques can be used to help standardize and improve the readability of your code Manybasic errors can be avoided in this way However, even if you follow all these suggestions, your code stillcan't be guaranteed to be bug-free Let's look at some of the errors that may plague your code

Conversion Function Return Datatype

Convert.ToInt16 16 bit signed IntegerConvert.ToInt32 32 bit signed IntegerConvert.ToInt64 64 bit signed Integer

Trang 3

Sources of Errors

The errors that occur in an ASP.NET page can be grouped into four categories:

Parser errors: These occur because of incorrect syntax or bad grammar within the ASP.NET page

Compilation errors: These are also syntax errors, but they occur due to statements that are notrecognized by the language compiler, rather than ASP.NET itself For example, using If (capital

I) instead of if, or not providing a closing bracket to a forloop, will result in a compilationerror The difference between the parser error and compilation error is that the parser erroroccurs when there is a syntax error in the ASP.NET page, and the ASP.NET parser catches it,whereas the compilation error occurs when there is a syntax error in the C# code block

Configuration errors: These occur because of the incorrect syntax or structure of a configuration

file An ASP.NET configuration file is a text file in XML format, and contains a hierarchical

structure that stores application-wide configuration settings There can be one configuration filefor every application on your Web server These configuration files are all named web.config, irrespective of the application's name. There is also a single configuration file calledmachine.configthat contains information that applies to every application on a singlemachine We will discuss configuration files in detail in Chapter 15, although we do touch

upon them again later in this chapter

Runtime or logical errors: As the name implies, these errors are not detected during compilation

or parsing, but occur during execution For example, when the user enters letters into a fieldthat expects numbers, and your program assigns that entry to an integer variable, you will get aruntime error when the code tries to execute These are also known as logical errors

Now let's look at some specific examples that fall into the above categories

Syntax Errors

As the name suggests, these errors occur when there are problems in the syntax of the code Parser andcompilation errors fall under this category These are usually the first errors encountered when

developing ASP.NET pages There are several reasons why these errors occur:

A typo or bad grammar in the code syntax: For example, instead of typing <asp:textbox>forcreating a TextBoxcontrol in your page, you type <asp:textbx>, then the browser shows anerror

Incorrect code syntax: For instance, when creating a textbox control, you might forget to close thetag (as <asp:TextBox id="txtName" runat="server">when it should actually be

<asp:TextBox id="txtName" runat="server"/>)

Combining or splitting keywords between languages: I make this error quite a lot If you've beencoding in another language and come back to coding in C#, you might forget brackets, or typekeywords in the wrong case

Not closing a construct properly: This error occurs if we forget to close a construct, such as a forloop or a nested ifstatement Take a look at this example:

if condition1 {

Trang 4

Let's look at an example of creating a syntax error (a parser error) and then see how ASP.NET responds

to it

Try It Out Syntax Error

1. Open Web Matrix and type the following lines of code into the AllWindow Make a spellingmistake when creating the textbox control, as highlighted in the following code:

<form method="post" action="syntaxerror.aspx" runat="server">

<asp:TetBox id="txtQuantity" runat="server" />

Trang 5

However, what you actually see is Figure 14-2:

Figure 14-2

How It Works

As the error message clearly states, the ASP.NET parser points to Line 7, and asks us to check the details.You can see that a spelling mistake exists, Tetboxinstead of TextBox If you correct the spelling mistakeand rerun the code, you'll get the expected result

Errors of this kind are very common but are usually quick and easy to fix, since the error messageprovides a detailed breakdown of the error and the line on which it occurs

Now we will look at a syntax error that will generate a compilation error

Try It Out Generate a Compiler Error

1. Create a new file called compilationerror.aspx, and type the following code into the WebMatrix Allwindow:

Trang 6

<%@ Page language="C#" Debug="true" %>

<script language="C#" runat="server">

public void CompleteOrder(Object sender, EventArgs e)

<form method="post" action="manualtrapping.aspx" runat="server">

<asp:Label text="Order Quantity" runat="server" />

<asp:TextBox id="txtQuantity" runat="server" />

Trang 7

Figure 14-3

How It Works

We typed Ifat the beginning of our control block instead of if As expected, when we tried to run thecompilationerror.aspxfile in the browser, we got an error message It tells us we have a compilererror in Line 5and even attempts to tell us how to fix it (In this case it is rather misleading as it tells us

we are missing a semicolon, when in fact, the ifstatement is the part that is incorrect!)

These are just a few common examples of syntax errors There is no way we could provide a list of allpossible syntax errors that you might encounter, but the good news is that syntax errors are easy to findand fix

Logical (Runtime) Errors

The second type of error is the Logical Error Unfortunately, it is relatively more difficult to find and fix.

Logical errors become apparent during runtime As the name implies, these errors occur due to mistakes

in programming logic Some of the more common reasons for these errors are:

Trang 8

Division by zero: This dreaded error that has been around since the days of valve-based computers It occurs when your program divides a number by zero But why in the world do

we divide a number by zero? In most cases, this occurs because the program divides a number

by an integer that should contain a non-zero number, but for some reason, contains a zero

Type mismatch: Type mismatch errors occur when you try to work with incompatible data typesand inadvertently try to add a string to a number, or store a string in a date data type It is possible to avoid this error by explicitly converting the data type of a value before operating on

it We will talk about variable data type conversion later in this chapter

Incorrect output: This type of error occurs when you use a function that returns output that's different from what you are expecting in your program

Use of a non-existent object: This type of error occurs when you try to use an object that wasnever created, or when an attempt to create the object failed

Mistaken assumptions: This is another common error, and should be corrected during thetesting phase (if one exists) This type of error occurs when the programmer uses an incorrectassumption in the program This can happen, for instance, in a program that adds withdrawalamounts to a current balance, instead of subtracting them

Processing invalid data: This type of error occurs when the program accepts invalid data Anexample of this would be a library checkout program that accepts a book's return date asFebruary 29, 2003, in which case, you may not have to return the book for a while!

While this is far from being a complete list of all possible logical errors, it should give you a feel for what

to look out for when testing your code

Try It Out Generate a Runtime Error

1. Open compilationerror.aspxin Web Matrix, go to the AllWindow, and make the followingchange to the case of the ifstatement:

public void CompleteOrder(Object sender, EventArgs e)

2. Save the file as runtimeError.aspx

3. View the runtimeError.aspxfile using the browser Provide a non-numeric value, such asABC, to the order quantity textbox, and click the Complete Orderbutton Figure 14-4 shows theresult:

Trang 9

Figure 14-4

How It Works

Our control block validates input for null values, and for numeric values that are equal to or less thanzero It does not check input for other non-numeric input values The code generated a runtime errorwhen the ConvertTo.Int32()function tried to convert a non-numeric entry to an integer field Theprocess of checking for this type of errors is called validation To validate the data entry values, yourcontrol block should have an extra couple of lines as follows:

else if (Convert.ToInt32(txtQuantity.Text) <= 0)

{

lblOrderConfirm.Text = "Please provide a Quantity greater than 0.";

}

Let's take a closer look at validating user input

Trapping Invalid Data

Testing your code by supplying both legal and illegal values is crucial for the proper functioning of yourprogram Your program should return expected results when providing legal values, and handle errorswhen supplied with illegal values In this section, we'll talk about ways to handle the illegal valuessupplied to your program We have two objectives here:

Trang 10

❑ Prevent the occurrence of errors that may leave you with many disgruntled users

❑ Prevent your program from accepting and using illegal values

There are two main techniques used to fulfill these objectives: manual trapping and using validation

controls.

Manual Trapping

When building the application, you could create error traps to catch illegal values before they get into the

page execution, where they might halt the execution of the page or provide invalid results How do youblock illegal values from sneaking into page processing? Let's develop a page that accepts order quantityfrom the user

Try It Out Catching Illegal Values

1. Open runtimeError.aspxin Web Matrix and make the following changes in the AllWindow:

<%@ Page Language="c#" Debug="true" %>

<script Language="c#" runat="server">

void CompleteOrder(object sender, EventArgs e)

lblOrderConfirm.Text =

"Please provide only numbers in Quantity field.";

}else{lblOrderConfirm.Text =

"Please provide a Quantity greater than 0.";

}}

Trang 11

2. Save the file as manualtrapping.aspx.

3. Load this file using your browser Figure 14-5 shows the result of providing an order quantity of

Notice that we have added an extra directive to the page calls:

<%@ Page language="C#" Debug="true" %>

This will enable us to view detailed error messages throughout the course of the chapter How thisworks will become clearer as we progress

We are using two Labelcontrols: a TextBoxcontrol and a Buttoncontrol The first Labelcontrol is thelabel for the order quantity textbox:

<asp:Label text="Order Quantity" runat="server" />

The second label control called lblOrderConfirmis used to display a message after processing theorder, indicating whether the order was successfully placed or not:

<asp:Label id="lblOrderConfirm" runat="server"/>

The textbox accepts an entry from the user – the order quantity:

<asp:TextBox id="txtQuantity" runat="server" />

The button calls the CompleteOrder()function when clicked:

<asp:Button id="btnComplete_Order" Text="Complete Order"

onclick="CompleteOrder"

Trang 12

lblOrderConfirm.Text =

"Please provide only numbers in Quantity field.";}

else{lblOrderConfirm.Text =

"Please provide a Quantity greater than 0."; }

Using Validation Controls

The second technique is to use one or more of several validation controls provided by ASP.NET (refer to

Chapter 10 for a detailed discussion on validation controls.)

Validation controls are used to validate user input For instance, you could use the

RequiredFieldValidatorcontrol to ensure that users enter a value to a textbox By doing this, youcould avoid runtime errors that occur because of your program using a null (unknown value), when it isexpecting an ’entry’ from the user

Trang 13

By using one of the many validation controls provided by ASP.NET, you could present the users with amessage informing them about the incorrect value supplied, and the value your program is expecting.This prevents the program from processing an illegal value and developing an error.

Let's look at an example to demonstrate how to use these controls We'll use the

RequiredFieldValidatorto ensure that the user provides a value for the Order Quantityfield.Try It Out Using RequiredFieldValidator

1. Open manualtrapping.aspx(from the previous exercise) in Web Matrix, and make thefollowing changes in the AllWindow:

<form method="post" action="usingvalidationcontrol.aspx" runat="server">

<asp:Label text="Order Quantity" runat="server" />

<asp:TextBox id="txtQuantity" runat="server" />

<asp:RequiredFieldValidator ControlToValidate="txtQuantity" runat="server"

ErrorMessage="Please enter a value in the Order Quantity Field">

2. Save this file as usingvalidationcontrol.aspx

3. Use your browser to open usingvalidationcontrol.aspx If you try to complete the orderwithout entering anything, you're presented with the request that you see in Figure 14-6:

Trang 14

In this case, we are validating the order quantitytextbox The ErrorMessage property is used toprovide an error message when the user does not enter a value to the order quantity field.

ErrorMessage="Please enter a value in the Order Quantity Field">

The validation control saves us the extra second guessing of typical mistakes a user might make

System Errors

These errors are generated by ASP.NET itself They may be due to malfunctioning code, a bug in

ASP.NET, or even one in the CLR Although you could find this type of error, rectifying it is usually notpossible – particularly if it is an ASP.NET or CLR error

Other errors that can be placed in this category are those that arise due to the failure of a Web server orcomponent, a hardware failure, or a lack of server memory

When an error occurs in an ASP.NET page, the error details are sent to the client However, ASP.NET bydefault shows detailed error information only to a local client

A local client is a browser running on the same machine as the Web server and therefore only viewable

by the site administrator For instance, if you create the ASP.NET examples in this book on a machinerunning a Web server, and access them using a browser on the same machine (as you would do withWeb Matrix), then the browser is a local client If this was deployed on a network using IIS, you mightsee the error, but other users on the network would just receive a generic "something's wrong" kind ofmessage

So, the fact that ASP.NET sends detailed information about errors to local clients is actually very helpful

to the developer during the development phase

However well you plan, it is difficult, if not impossible, to catch every bug in advance So, what do we

do if our well-constructed code still doesn't work? We will discuss this topic next

Let's go back to the local client scenario ASP.NET displays a call-stack when a runtime error occurs A

call-stack contains a series of function calls that lead up to an error Before you do this, delete (or

rename) any web.configfiles residing with your samples; otherwise all errors generated will behandled by this file

Let's create a page that causes a runtime error

Trang 15

Try It Out Viewing the Call-Stack

1. Open Web Matrix and create a file called callStack.aspx Then type the following code intothe AllWindow:

<%@ Page Language="c#" Debug="true" %>

<script language="c#" runat="server">

Trang 16

The information provided under the Source Errorsection is useful in locating the line in which theerror occurred The display of this information is controlled by the Debugmode.

Debug Mode

If Debugmode is enabled, the Source Errorsection of the error message is displayed as part of the errormessage that pinpoints the location in the code that generated the error If Debugmode is disabled, theSource Errorsection is not displayed

Now the question is: where and how can we set the value for Debugmode?

It can be set in two different places The first place should be familiar as we have used it twice alreadywithin this chapter You can set it at every page within the Pagedirective at the top of the page, asshown below:

<%@ Page Debug="true" %>

To disable it, you can set it to false:

<%@ Page Debug="false" %>

If the Debugmode is set like this (at the page level), the setting is applied only to that specific page

Let's return to our previous example, and disable the Debugmode at the page level:

Try It Out Disable the Debug Mode

1. Open the callstack.aspxfile in Web Matrix, and in the Allwindow, insert the following line

at the top of the page – don't replace the existing declaration:

<%@ Page Language="C#" Debug="false" %>

Trang 17

2. Save the file as debugmode.aspxand access the page using the browser You will see an errorpage as shown in Figure 14-8:

As mentioned a moment ago, there are two ways to set the Debugmode The second way is to set it at

the application level, using the <compilation>configuration section in the configuration file (see Chapter

15).

Trang 18

Setting the Debugmode at the application level will display the Source Errorsection in the error messagefor all the files under the application This has a performance overhead though, so before moving yourapplication to a production environment, make sure you disable the Debugmode.

Tracing

When developing an application, we execute the page at different levels of development, and foreffective debugging, we always need to see the values assigned to variables and the state of differentconditional constructs at different stages of execution In ASP, developers used the ubiquitous

Response.Writestatement to display this information The downside of this is that while completingthe application development, the developer had to go to every page and either comment or remove theResponse.Writestatements they created for testing purposes ASP.NET provides a new feature tobypass all of this It is the Tracecapability

The Trace feature provides a range of information about the page, including request time, performancedata, server variables, and most importantly, any message added by the developers It is disabled bydefault Like the debugmode, tracing can be either enabled or disabled at either the page (or the

application) level We'll now consider these levels in more detail

Page-Level Tracing

Tracing can be enabled at the page level to display trace information using the Pagedirective's Traceattribute, as shown below:

<%@ Page Trace = "true" %>

Tracing can be disabled using:

<%@ Page Trace = "false" %>

When tracing is enabled, the trace information is displayed underneath the page's contents Let's create asimple ASP.NET page with a TextBoxand a Labelcontrol, and enable tracing at the page level

Try It Out Enabling Trace at the Page Level

1. Open Web Matrix, create a page called pageleveltracing.aspx, and type in the followingcode to the AllWindow:

<form method="post" action="pageleveltracing.aspx" runat="server">

<asp:label text="Name" runat="server" />

<asp:textbox name="txtName" runat="server" />

</form>

</body>

</html>

Trang 19

2. Save this file and view it using the browser as shown in Figure 14-9:

Figure 14-10

Trang 20

Trace Information: This is the section in which the actual trace information is displayed alongwith the messages written by developers As shown in Figure 14-11, this section displays thecategory, the message, the time since the first message, and the most recent message displayed:

Figure 14-11

Control Tree: This section displays details about the different controls used in the page Thedetails include the ID provided for the control, the type of control used, and its position amongother controls, as shown in Figure 14-12:

Trang 21

Server Variables: This section displays all the members of the Server Variables collection asshown in Figure 14-15:

Figure 14-15

Now that we've introduced the information displayed in the trace page, let's talk about techniques used

to write a message to the Trace Informationsection, and get updates on what goes on behind the scenes asyour code is executed

Writing to the Trace Log

Each ASP.NET page provides a Traceobject that can be used to write messages to the trace log You canuse two methods to write messages to the trace log:

❑ Trace.Write()

❑ Trace.Warn()

The messages are only displayed when tracing is enabled.

Both methods are used to write messages to the trace log, but when using the Trace.Warn()method,the messages are displayed in red You may want to use Trace.Warn()for writing (and highlighting)unexpected results or incorrect values for variables in your program Let's create an example that showshow to use these methods

Try It Out Writing to the Trace Log

1. Open Web Matrix, create a file called writetotrace.aspx, and type the following code into AllWindow:

Trang 22

// Trace.Write ["Category", "Message to be displayed"];

// Trace.Warn ["Category", "Message to be displayed"];

Trang 23

How It Works

The first thing we do is declare intCounter(which we're using as a label) as an integer data type, andassign a value of 1to it:

int intCounter=1;

We write a message to the trace log, which says our variable has been initialized:

Trace.Write ("FirstCategory", "Variable is initialized");

The next three lines of code constitute a loop, so that while intCounteris greater than 10, it will beincremented:

displayed for that page

Application-level tracing is set using the <trace>section in the configuration file (web.config)discussed earlier The following is an example of the <trace>section:

Trang 24

Trace.axd: The Trace Information Log

When application-level tracing is enabled (there has to be a web.configfile present for this – you cancopy the previous code and save it as web.configjust to test it), the trace information is logged to therrace.axdfile This file can be accessed using the URL for your application, followed by trace.axd –for example, http://yourwebservername/applicationname/trace.axd

Figure 14-17 shows how the trace.axdfile looks in the browser, after another browser has made arequest to manualtrapping.aspxand received a response from the server:

On Error Goto?

If you have a background in Visual Basic, you might be asking yourself whether you can use syntax like

On Error Resume Nextin C#, and the short answer is, no you cannot! C#'s built-in error handling syntax

is based on structured exception handling Structured exception handling in C# does not allow you to

simply skip the line of code producing the error and proceed with the next one Such a function is OKfor a script-based application such as a traditional ASP page, but for the object-oriented world of C# andASP.NET, you need something more robust Structured exception handling also largely replaces the

Trang 25

crude error handling offered by On Error Goto Labelsyntax as well C# also does not have any

equivalent to the Visual Basic Errobject

Structured Error Handling

We have already come across structured exception handling in this book wherever we have actuallyneeded it:

❑ We used it to deal with situations where conversion between data types might fail and generate

In all cases, we referred to this point in the book where we look closely at implementing error handling.However, to provide a complete picture of what C# error handling can achieve, we are going right back

to the basics

So what do we mean by structured error handling? Pretty much just that: handling errors via a

particular structure Lines of code are grouped together, and different handlers are provided to handledifferent errors within those groups The following list shows the sequence of events that take placewhen using structured error handling:

1. We execute one or more lines of code in a group They might execute without an error, or theymight generate one or many different kinds of errors

2. If errors are generated, a handler (which you will have defined) corresponding to the error will

be called If there is no error, no handler will be called

Two important things need to be done for effectively using structured error handling:

❑ Creating a group of lines or a block of code

❑ Creating handlers for the different kinds of errors that could occur when the code block isexecuted

Before launching into this subject, we need to introduce the concept of exceptions

Exceptions

An exception is any error condition or unexpected behavior that occurs during the execution of a

program, and consequently disrupts the normal flow of execution – in fact, the term is just shorthand

for exceptional event If an error occurs within a method call, the method creates an exception object and

You can also define a generic handler that handles any errors for which you did not

define a specific handler.

Trang 26

hands it off to the runtime system This object contains information detailing the type of exception thatwas raised and the state of the program at the time.

The exception event is thrown by the code that calls the event The code can either catch the exception(and try to handle the problem), or pass it on up to the code that called that code, and so on up theinvocation stack If it reaches the top of the stack without being caught by a handler somewhere alongthe way, the program will crash Before talking about how to handle exceptions, we'll briefly introduceyou to the exception class, and its properties

The Exception Class

.NET Framework provides a System.Exceptionclass, which acts as the base class for all exceptions.The Exceptionclass contains properties that aid our understanding of the exception The followingtable summarizes the different properties within Exceptionclass:

Property Description

StackTrace This property contains the stack trace (which shows the sequence of

nested function calls your program has executed.) This can be used to determine the location of the error occurrence

Message This property contains a message about the error

InnerException This property is used to create and store a series of exceptions during

exception handling For example, imagine if a piece of your code threw an exception The exception, and its handler, could be stored in theInnerException property of that handler You could then reference the exception, see how it was handled, and, based on that information, perhaps create a more effective handler This can be very useful when you are reviewing the execution of a piece of troublesome code InnerException can also be used to store an exception that occurred in a previous piece of code

Source This property contains information about the application that

generates the error

TargetSite This property contains information about the method that throws the

exception

HelpLink This property is used to provide the URL for a file containing help

information about an exception that occurs

Depending on whether the exception stems from the program itself or from the CLR,

you may or may not be able to recover from the exception While you can recover

from most application exceptions, you can seldom recover from a runtime exception.

Trang 27

The two important exception classes that inherit from System.Exceptionare ApplicationExceptionand SystemException The SystemExceptionclass is thrown by the runtime while the

ApplicationExceptionclass is thrown by an application Let's now look at some actual code thatmakes structured error handling possible

Let's explain what each block means

The tryblock contains all the code that might cause a runtime exception This can be a single line ofcode or multiple lines There is not much more to say on this, as there are no parameters to consider, norany limitations on the code you can wrap in a tryblock However, a tryblock by itself is not valid codeand immediately after the closing brace, you must have a catch(or finally) block to handle anyexceptions that could be raised Therefore, the code construct that fulfils the minimum requirements forstructured exception handling would look like this (we have seen many instances of this earlier on tinthis book):

Multiple catch Blocks

Atryblock can be followed by more than one catchblocks We said earlier on, that you can writeexception handlers that respond to different types of errors as well as a general purpose error handler,that is able to deal with any error at all In C#, this is achieved by stacking catchblocks one afteranother If an exception is thrown from the tryblock, the code will pass the Exceptionobject createddown the chain of catchblocks until there is a match On the other hand, if there is no match, theexception is passed to the.NET runtime and you will get an unhandled exception error page as we sawearlier

Trang 28

Let's illustrate this by using some pseudo-code:

Any variables declared in the code blocks in C# are local in scope, so if you want

variables to be available to the try , catch , and finally blocks, they must be

declared before the try block starts.

Trang 29

catch (SystemException se)

any NET exception that is thrown, including system exceptions In other words, if a SystemException

is thrown, it will be caught by the catch (Exception e), because it is first in the list, and becausederived exception types can be caught by error handlers matching the base Exceptiontype Therefore,the second and more specific error handler can never be executed because it is unreachable code Thecompiler will flag this up as an error

The rule is that you place all error handlers in order, from the most specific to the least specific So, doesthat mean that code blocks preceded with catch (Exception e)always come last in the set? Well, no –you can define a catchblock that is even more general that this one The catch (Exception e)blockcan deal with any NET-related exception but it cannot deal with any exceptions thrown by objectsoutside NET, such as the ones from the Windows operating system (OS) To trap any error at all,regardless of its origin, C# allows you to use a catchwith no parameter at all:

What You Can Put in a catch Block

There is no limit to what you can put in a catchblock Normally, you would generate some message toinform the user that something exceptional had occurred or write the information to an error log.Alternatively, you could add some recovery code to deal with the error and bring the application back to

a normal state, without the user even knowing that anything happened at all In most cases, you willwant to make use of the contents of the exception object that was created when the exception wasthrown

The general Exceptionobject only provides general information on an error, which may or may not beuseful to you A more specific exception object that uses one of the derived classes would contain morespecific information about the error, which would also make it easier to deal with For this reason, it isalways best to include as many specific error handlers as you deem reasonable, when you know

beforehand what kind of exceptions are likely to occur

The following code example would display the contents of the Messageproperty of an

Trang 30

The general-purpose error handler should only be used if you do not know what type of exception islikely to occur, or as a catch-all error handler for any unlikely exceptions You can also use this errorhandler if you are only outputting a simple error message:

catch (Exception e)

{

Response.Write("You must type your name in the box");

}

Here the compiler may warn you that you are not using the Exceptionobject e(it's not necessary that

you have to use this) If you want to eliminate this compiler warning altogether, you can use the ultimate

general-purpose error handler:

The finallyblock, if defined, will be executed either after the error has been handled, or after the code

in the tryblock has been executed, depending on whether an error occurred or not The finallyblock

is typically used to do cleanup tasks, such as releasing resources, closing objects, and so on The syntax isvery simple:

Generating Exceptions Using throw

Up until now, we have assumed that we only handle exceptions that are thrown by the NET runtimeand that we create error handlers that are matched to the various exception objects that could be

produced We have even considered exceptions that are thrown by code outside the control of the NETruntime However, we can take control of the exception generation process ourselves by manuallygenerating an exception in response to a given set of conditions Any code can be configured to generate

an exception, and the syntax for doing this is as follows:

if (something happens)

{

throw new Exception("An error has occurred");

}

An exception is generated whenever the above condition evaluates to trueand will contain the message

An error has occurred If left alone, the program execution will immediately terminate, therefore the code

Trang 31

containing the throwstatement should be enclosed in a tryblock, and followed by an appropriatecatchblock However, this need not be the case

Athrowstatement could well be included in a function without any tryand catchblocks defined atall This means that the function call itself must be placed in a tryblock, and the code calling thefunction must take responsibility for handling any error that could be generated by the function Say wehave a function like this:

double MayThrowError(double a, double b)

documentation for a class to inform you whether an exception could be thrown by a function, and if so,what kind If you should go on to create a function for general use that can throw an exception, youshould inform your potential users of this in order to prevent them from receiving a nasty surprise!Another way of manually generating exceptions is by using the checkedkeyword It is applied to astatement that can fail, to make sure that a runtime exception is thrown We saw this when consideringoverflows of variable types, but it can also be applied to other potential problem areas such as data typeconversions If you use checkedin your code, you must also use try catchblocks

Now we've done the theory, let's try an example

Try It Out Using try catch finally

1. Create a new file called structuredErrorHandling.aspxin Web Matrix and add the

following code within the AllWindow:

<script Language="C#" runat="server" >

Trang 32

void StructuredErrorHandling ()

{

try

{

int [] array = new int[9];

for(int intCounter=0; intCounter <= 9; intCounter++)

// Handler for index out of range exception

catch (IndexOutOfRangeException ex)

Trang 33

Figure 14-18

How It Works

In the StructuredErrorHandling()function, the tryblock encloses all the code we want to execute

We create an integer array and we attempt to loop through it:

for(int intCounter=0; intCounter <= 9; intCounter++)

We have made a deliberate mistake in the code, in that we are attempting to loop through ten elements

in an array whereas there actually are only nine An exception will be thrown

There are two catchblocks defined One for the expected IndexOutOfRangeExceptionobject:

catch (IndexOutOfRangeException ex)

{

Response.Write("Error Occurred"+ "<br>" + ex.ToString() + "<br>");}

Trang 34

The other one is a generic catch-all handler, which should not be executed in this code, but is there just

Response.Write("Function call completed" + "<br>");

Nested Try Blocks

Structured exception handling can be extended to allow for multiple levels of error handling usingnested tryblocks This enables you to exert more control over the error handling process than can beachieved using a single tryblock You can do two things with nested tryblocks that may not beachievable using just one You can modify the type of exception thrown, and you can enable differenttypes of exception to be handled in different places in your code The syntax for implementing nestedtryblocks looks like this:

Trang 35

This is how it works If the code at the point marked [1]fails, then the catchblock marked [5]will becalled upon to handle it This corresponds with the behavior already outlined for a single tryblock Incase of a failure occurring before the inner tryblock starts, the page will not even be aware that theinner tryblock exists, as all code from the point where the exception occurs is ignored.

If, however, the code in the inner tryblock fails, marked by [2], then control passes to catchblocks[3]or [4], which will process the error Then the inner finallyblock is executed and the code

execution continues as normal until the end of the outer tryblock, where the outer finallyblock isexecuted

This is all well and good, but what if none of the inner catchblocks can handle the error? What

happens then? Well, the NET runtime will keep looking for a handler to deal with the exception

generated It will run the code in the inner finallyblock before leaving the outer tryblock (passingover any code that occurs after the end of the inner tryblock) The set of catchblocks following theouter tryblock are examined for a match and, if there is one, then the code for that particular catchblock is executed If even at this point there is no match, the outer finallyblock is run and controlpasses to the NET runtime

So what happens if the code in the catchblocks [3]and [4]fails? We have not considered this before

in this section, but code can fail even in error handlers! In such situations, NET runtime will, in the firstinstance, look for an error handler in any catchblock associated with the outer tryblock (block [5]inthis case)

This passing around of exception objects between catchblocks can actually be used to our advantage

We have said before, that the benefit of using nested tryblocks is that you can modify the exception thatwas originally thrown You might want to do this because the exception object that was thrown mightnot be the root cause of the problem; you might want to look at other possibilities

So if you have code like that shown in the following snippet and an ApplicationExceptionis thrown,

it will be caught by the appropriate catchblock However, on further investigation, you might find thatthe real problem lies with a missing file Then, you can generate a new exception to deal with thissituation by using throw In the code, the line marked in bold achieves this The new exception isthrown with an appropriate message as well as a reference to the original ApplicationExceptionstored in the InnerExceptionproperty:

Trang 36

Handling Errors Programmatically

We can now handle errors using try…catchblocks, but some exceptions may still sneak through.ASP.NET provides us with two more methods that can be used to handle any errors that are

unaccounted for, and provide a friendly message to the user, instead of the default runtime error screen

The exception handler might not be defined in your class at all – it might be a NET

Framework base class function; the rules for passing exceptions around are handled

by the NET Framework and so are not dependent on the way the code is structured.

Indeed, it is possible for code written in Visual Basic NET to throw an exception

that is then handled by code written in C#.

Trang 37

The two methods are:

To see how it works, let's take our previous example and modify it to use the Page_Error()method.Here, we created an error by storing a string to an integer datatype, and we used the Trystatement tohandle exceptions This time, we'll just use the Page_Error()method to handle the exception:

Try It Out Using Page_Error()

1. Open structuredErrorHandling.aspxin Web Matrix, and make the following adjustmentswithin the AllWindow:

<script Language="c#" runat="server">

void PageLevelErrorTest()

{

// Remove opening try

int[] array = new int[9];

for(int intCounter=0; intCounter <= 9;intCounter++)

Trang 38

Figure 14-19

How It Works

We already know about the first half of this code, as it is the same as for the previous example However,it's the Page_Error()function that we're interested in:

void Page_Error(object sender, EventArgs e)

Within the Page_Error()method, we write a message to the user to say that an error has occurred, andget detailed error information from the server using the GetLastError()method of the

Serverobject:

Response.Write("Error occurred: " + Server.GetLastError().ToString());After displaying the message, we free up the server by using the ClearError()method of the Serverobject

The Page_Error()method is called whenever an unhandled exception is thrown within the page Thismethod could be used to catch the error, log the error to a log file, notify the administrator of the error

using e-mail, or store the error information to a database We will talk about this in the Notification and

Trang 39

The following example shows the usage of this method:

void Application_Error(object sender, EventArgs e)

{

//Handle the Error

//Provide code to log the error or send an email

}

Error Notification and Logging

In this section, we will talk about the techniques that are used to log errors to the Windows event log,and notify a site manager or administrator of the occurrence of the error

Customized Error Messages

The next question is: what if the development server is on a different machine? ASP.NET allows you tospecify whether you want the detailed message to be displayed on the local client, on remote clients, orboth You can specify this information using the <customErrors>section in the Web configuration file,web.config We'll discuss the web.configfile later in the book (see Chapter 15 for more details); for

now, just create a new file in your application folder called web.config, so that you can demonstratehow to handle custom errors The following example shows a sample setting for the <customErrors>section:

<configuration>

<system.web>

<customErrors defaultRedirect="userError.aspx" mode="On">

<error statusCode="404" redirect="PagenotFound.aspx" />

</customErrors>

</system.web>

</configuration>

As shown, the <customErrors>configuration section has two attributes The first is the

defaultRedirectattribute, and specifies the URL for the page to be redirected to when an erroroccurs The above configuration setting will redirect the user to a default error page, userError.aspxwhen an error occurs

The second attribute is the modeattribute, which takes three values: On, Off,and RemoteOnly On,specifies that the custom error is enabled; the users will be redirected to the custom error page specified

in the defaultRedirectattribute Offspecifies that the custom error is disabled; the users will not be

redirected to a customized error page, but to a general non-informative one RemoteOnly, the defaultsetting, specifies that only remote (and not local) clients should be redirected to the custom error page.The <customError>configuration section contains an <error>sub tag, which is used to specify errorpages for different errors In the above example, the PagenotFound.aspxpage has been specified as the

All settings in web.config file have to be enclosed with <configuration> and

<system.web> tags In addition, make sure that you copy the upper and lower case of

this code exactly as web.config is case-sensitive.

Trang 40

error page when HTTP 404error occurs You could provide multiple <error>sub tags for different errorcodes

Let's create the two friendly error pages, userError.aspxand PagenotFound.aspx, specified in theconfiguration file

Try It Out Creating Error Pages

1. Create a Web configuration file in BegASPNet11/ch14 To do this, go to Web Matrix and choosethe Web.configoption in the third row of the Add New Filedialog Don't worry if there is already

a web.configfile there; it is OK to overwrite it

2. Delete all of the code that is automatically generated, as it only needs to consist of the following

<customErrors>section, which you should type in as follows:

<configuration>

<system.web>

<customErrors defaultRedirect="userError.aspx" mode="On">

<error statusCode="404" redirect="PagenotFound.aspx" />

<h2> An error has occurred in executing this page Sorry for the

inconvenience The site administrator is aware of this error occurrence

</h2>

</body>

</html>

4. Create the PagenotFound.aspxpage Create another file in Web Matrix and enter the

following code into the AllWindow:

Ngày đăng: 13/08/2014, 04:21

TỪ KHÓA LIÊN QUAN