Error Handling for the User Interface O BJECTIVES

Size: px
Start display at page:

Download "Error Handling for the User Interface O BJECTIVES"

Transcription

1 CH04 4/7/03 11:03 AM Page 281 O BJECTIVES This chapter covers the following Microsoft-specified objectives for the Creating User Services section of Exam , Developing and Implementing Web Applications with Microsoft Visual C#.NET and Microsoft Visual Studio.NET : Implement error handling in the user interface. Configure custom error pages. Implement Global.asax, application, page-level, and page event error handling.. When you run a Web application, it might encounter problems that should not occur in the normal course of operations. For example, the database server is down, a file is missing, or a user has entered improper values. A good Web application must recover gracefully from these problems rather than abruptly terminating page execution. Microsoft.NET Framework provides structured exception handling through the use of try, catch, and finally blocks to help you catch these exceptional situations in your programs. There are predefined exception classes to represent different types of exceptions; you can also define your own exception handling classes and error messages that are specific to your application.. Exceptions that are not handled by structured exception handling are called unhandled exceptions. When such exceptions are unhandled, the Web page displays the raw error messages to the user. This is not user friendly (and can be a source of security leak). The.NET Framework allows you to create custom error pages to be displayed to the user. These custom error pages can be configured at both the page and application level. Objects, such as the Page or Application object, have an Error event that can be a suitable place to trap unmanaged errors. C H A P T E R 4 Error Handling for the User Interface

2 CH04 4/7/03 11:03 AM Page 282 O UTLINE S TUDY S TRATEGIES Introduction 283 Understanding Exceptions 283 Handling Exceptions 287 The try Block 288 The catch Block 288 The throw Statement 292 The finally Block 294 Creating and Using Custom Exceptions 298 Managing Unhandled Exceptions 304 Using Custom Error Pages 305 Setting a Custom Error Page for a Specific Page 309 Using Error Events 311 Using the Page.Error Event 311 Using the Application.Error Event 313. Review the Exception Handling Statements and the Best Practices for Exception Handling section of the Visual Studio.NET Combined Help Collection. The Visual Studio.NET Combined Help Collection is installed as part of the Visual Studio.NET installation.. Experiment with code that uses the try-catchfinally blocks. Use these blocks with various combinations, and inspect the differences in your code s output.. Know how to create custom exception classes and custom error messages; learn to implement them in a program.. Know how to configure custom error pages in the web.config file. Learn how to create a default error page for the application and some different error pages for various types of HTTP error codes.. Experiment with code that performs error handling at the Page_Error() or Application_Error() event handlers. Learn how to get the details of the error that occurred most recently in an application. Chapter Summary 319 Apply Your Knowledge 320

3 CH04 4/7/03 11:03 AM Page 283 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 283 INTRODUCTION Exception handling is an integral part of the.net Framework. The framework classes, as well as user-defined classes, throw exception objects to indicate unexpected problems in the code. The Framework Class Library (FCL) provides a huge set of exception classes representing various unforeseen conditions in the normal execution environment. If you feel the need to create custom exception classes to meet specific requirements of an application, you can do so by deriving a class from the ApplicationException class. An exception can be explicitly generated using the throw statement. This chapter introduces the try-catch-finally blocks that help you in catching exception objects to recover from error situations. Exceptions that are not handled by the try-catch block are called unhandled exceptions. When the errors are unhandled, the Web page that caused the error displays the error messages to the user. The.NET Framework also allows you to create custom user-friendly error pages to be displayed to the user rather than the default error message pages being displayed. These custom error pages can be configured at both the page and application level. You can trap unhandled exceptions at an object level, such as Page or Application. The Page_Error() event handler can be used to handle unhandled exceptions in a page, whereas the Application_Error() event handler can be used to handle unhandled exceptions thrown by all the Web pages of an application. UNDERSTANDING EXCEPTIONS An exception occurs when a program encounters any unexpected problems, such as running out of memory or attempting to read from a file that no longer exists. These problems are not necessarily caused by a programming error, but they mainly occur because of violations of assumptions that you might have made about the execution environment. When a program encounters an exception, the default behavior is to throw the exception, which generally translates to abruptly terminating the program after displaying an error message. This is not a

4 CH04 4/7/03 11:03 AM Page Part I DEVELOPING WEB APPLICATIONS characteristic of a robust application, and it will not make your program popular with users. Your program should be able to handle these exceptional situations and, if possible, gracefully recover from them. This is called exception handling. Proper use of exception handling can make your programs robust, as well as easy to develop and maintain. If you do not use exception handling properly, you might end up having a program that performs poorly, is harder to maintain, and is potentially misleading for users. Step by Step 4.1 demonstrates how an exception might occur in a program. Later in this chapter, I explain how to handle exceptions. FIGURE 4.1 The Mileage Efficiency Calculator Web form does not implement any exception handling for the user interface. STEP BY STEP 4.1 Exceptions in Web Applications 1. Create a new Visual C# ASP.NET Web Application project in the Visual Studio.NET IDE. Name the project 315C Add a new Web form to the project. Name it StepByStep4_1.aspx. 3. Place three TextBox controls (txtmiles, txtgallons, and txtefficiency) and a Button (btncalculate) on the Web form s surface and arrange them as shown in Figure 4.1. Add the Label controls as necessary. 4. Add the following code to the Click event handler of btncalculate: private void btncalculate_click( object sender, System.EventArgs e) // This code has no error checking. // If something goes wrong at run time, // it will throw an exception. decimal decmiles = Convert.ToDecimal( txtmiles.text); decimal decgallons = Convert.ToDecimal( txtgallons.text); decimal decefficiency = decmiles/decgallons; txtefficiency.text = String.Format( 0:n, decefficiency); 5. Set the Web form as the start page for the project.

5 CH04 4/7/03 11:03 AM Page 285 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE Run the project in Debug mode. Enter values for miles and gallons and click the Calculate button. The code calculates the mileage efficiency, as expected. Now enter the value 0 in the Gallons of Gas Used field and click the Calculate button. You will see that the program abruptly terminates by displaying error details in the Web page, as shown in Figure 4.2. FIGURE 4.2 When the project is run in debug mode, the development environment gives you a chance to analyze the problem when it encounters an exception. When you run the program in debug mode and the program throws an exception, the Web page displays a detailed error message. The detailed error message displays the lines of code where the error occurred in the Source Error part of the Web page. This is the default behavior of ASP.NET when the machine accessing the page is the Web server itself. If the page was instead accessed from a remote client, the default behavior of ASP.NET is to hide the details, as shown in Figure 4.3. If you need to see full error details from a remote browser, you can edit the <customerrors> element mode setting in the web.config application configuration file to set the mode to Off. I ll discuss more of this in the section Using Custom Error Pages later in the chapter.

6 CH04 4/7/03 11:03 AM Page Part I DEVELOPING WEB APPLICATIONS FIGURE 4.3 When the Web page is requested from a remote client, by default ASP.NET hides the error details from the user. The Common Language Runtime (CLR) views an exception as an object that encapsulates any information about the problems that occurred during program execution. The FCL provides two categories of exceptions: á ApplicationException Represents exceptions thrown by the applications. á SystemException Represents exceptions thrown by the CLR. Both of these exception classes derive from the base Exception class. The Exception class implements the common functionality for exception handling. Neither the ApplicationException class nor the SystemException class adds any new functionality to the Exception class. These classes exist just to differentiate exceptions in applications from exceptions in the CLR. Table 4.1 lists the important properties of all three of these classes.

7 CH04 4/7/03 11:03 AM Page 287 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 287 TABLE 4.1 I M P O R TA N T P R O P E R T I E S O F T H E Exception C L A S S Property HelpLink InnerException Description Specifies the uniform resource locator (URL) of the help file associated with this exception. Specifies an exception associated with this exception. This property is helpful when a series of exceptions are involved. Each new exception can preserve the information about the previous exception by storing it in the InnerException property. Message Source StackTrace TargetSite Specifies textual information that indicates the reason for the error and provides possible resolutions. Specifies the name of the application causing the error. Specifies where an error occurred. If the debugging information is available, the stack trace includes the name of the source file and the program line number. Represents the method that throws the current exception. HANDLING EXCEPTIONS Implement error handling in the user interface Abruptly terminating a program when an exception occurs is not a good idea. An application should be able to handle the exception and try to recover from it, if possible. If recovery is not possible, you might take other steps, such as notifying the user and then gracefully terminating the program. The.NET Framework allows exception handling to interoperate among languages and across machines. For example, you can catch exceptions thrown by a Visual Basic.NET program from a Visual C#.NET program or vice versa. In fact, the.net Framework also allows you to handle exceptions thrown by legacy Component Object Model (COM) applications and legacy non-com Windows applications. Exception handling is such an integral part of the.net Framework that when you look for a method reference in the product documentation, there is always a section specifying what exceptions a call to that method might throw. You can handle exceptions in Visual C#.NET programs by using a combination of exception handling statements: try, catch, finally, and throw. In this section of the chapter, I will show you how these statements are used. TIP EXAM Floating-Point Types and Exceptions Operations involving floating-point types never produce exceptions. Instead, in exceptional situations, floating-point operations are evaluated using the following rules: If the result of a floating-point operation is too small for the destination format, the result of the operation becomes positive zero or negative zero. If the result of a floating-point operation is too large for the destination format, the result of the operation becomes positive infinity or negative infinity. If a floating-point operation is invalid, the result of the operation becomes NaN (Not a Number).

8 CH04 4/7/03 11:03 AM Page Part I DEVELOPING WEB APPLICATIONS The try Block You should place code that might cause exceptions in a try block. A typical try block will look like the following: try // code that may cause exception You can place any valid C# statements inside a try block, including another try block or a call to a method that places some of its statements inside a try block. The point is that at runtime you might have a hierarchy of try blocks placed inside each other. When an exception occurs at any point, rather than executing any further lines of code, the CLR searches for the nearest try block that encloses this code. The control is then passed to a matching catch block (if any) and then to the finally block associated with this try block. A try block cannot exist on its own; it must be immediately followed either by one or more catch blocks or by a finally block. The catch Block You can have several catch blocks immediately following a try block. Each catch block handles an exception of a particular type. When an exception occurs in a statement placed inside the try block, the CLR looks for a matching catch block that is capable of handling that type of exception. A typical try-catch block looks like this: try // code that may cause exception catch(exceptiontypea) // Statements to handle errors // occurring in the associated try block catch(exceptiontypeb) // Statements to handle errors occurring // in the associated try block The formula that the CLR uses to match the exception is simple. It looks for the first catch block with either the exact same exception or any of the exception s base classes. For example, a

9 CH04 4/7/03 11:03 AM Page 289 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 289 DivideByZeroException exception would match with any of these exceptions: DivideByZeroException, ArithmeticException, SystemException, and Exception. In the case of multiple catch blocks, only the first matching catch block is executed. All other catch blocks are ignored. When you write multiple catch blocks, you need to arrange them from specific exception types to more general exception types. For example, the catch block for catching DivideByZeroException exceptions should always precede the catch block for catching ArithmeticException exceptions, because DivideByZeroException exception derives from ArithmeticException exception and is therefore more specific than the latter. The compiler flags an error if you do not follow this rule. A try block need not necessarily have a catch block associated with it; but in that case, it must have a finally block associated with it. Step by Step 4.2 shows how to use a try-catch block to handle exceptions. STEP BY STEP 4.2 Using a try-catch Block to Handle Exceptions 1. Add a new Web form to the project. Name it StepByStep4_2.aspx. 2. Create a form similar to the one created in Step by Step 4.1 (Figure 4.1) with the same names for controls. Add a Label control (lblmessage) to the form. 3. Add the following code to the Click event handler of btncalculate: private void btncalculate_click( object sender, System.EventArgs e) // Put all the code that may require graceful // error recovery in a try block try decimal decmiles = Convert.ToDecimal(txtMiles.Text); decimal decgallons = Convert.ToDecimal(txtGallons.Text); decimal decefficiency = decmiles/decgallons; txtefficiency.text = continued NOTE Exception Handling Hierarchy If there is no matching catch block, you end up having an unhandled exception. The unhandled exception is propagated back to its caller code (the code that called the current method). If the exception is not handled there, it will propagate further up the hierarchy of method calls. If the exception is not handled anywhere, it goes to the CLR for processing. The CLR s default behavior is to immediately terminate the processing of the Web page.

10 CH04 4/7/03 11:03 AM Page Part I DEVELOPING WEB APPLICATIONS continues String.Format( 0:n, decefficiency); // try block should at least have one catch // or a finally block. catch blocks should be // in order from specific to generalized // exceptions, otherwise compilation // generates an error catch (FormatException fe) string msg = String.Format( Message: 0<br> Stack Trace:<br> 1, fe.message, fe.stacktrace); lblmessage.text = fe.gettype().tostring() + <br> + msg; catch (DivideByZeroException dbze) string msg = String.Format( Message: 0<br> Stack Trace:<br> 1, dbze.message, dbze.stacktrace); lblmessage.text = dbze.gettype().tostring() + <br> + msg; // Catches all CLS-compliant exceptions catch(exception ex) string msg = String.Format( Message: 0<br> Stack Trace:<br> 1, ex.message, ex.stacktrace); lblmessage.text = ex.gettype().tostring() + <br> + msg; // Catches all other exception including the // NON-CLS compliant exceptions catch // Just rethrow the exception to the caller throw; 4. Set the Web form as the start page for the project. 5. Run the project. Enter values for miles and gallons and click on the Calculate button. The program calculates the mileage efficiency, as expected. Now enter the value 0 in the Gallons of Gas Used field and run the program. Instead of abruptly terminating and showing the error page (as in the earlier example), the program shows a message about DivideByZeroException exception (as shown in Figure 4.4) and continues running. Now enter some alphabetic characters in the fields instead of numbers and

11 CH04 4/7/03 11:03 AM Page 291 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 291 click the Calculate button. This time you get a FormatException message, and the program continues to run. Now try entering a large value for both fields. If the values are large enough, the program encounters an OverflowException exception, but because the program is catching all types of exceptions, it continues running. The program in Step by Step 4.2 displays the error message by using the Message property when an exception occurs. The StackTrace property lists the methods in the reverse order of their calling sequence. This helps you understand the logical flow of the program. In a real application, you might choose to try to automatically respond to the exceptions as well. When you write a catch block that catches exceptions of type Exception, it will catch all CLS-compliant exceptions. This means all exceptions, unless you are interacting with legacy COM or Windows 32-bit Application Programming Interface (Win32 API) code. If you want to catch all kinds of exceptions, whether CLScompliant or not, you can place a catch block with no specific type. A catch block like this has to be the last in the list of catch blocks because it is the most generic one. You might be thinking that it is a good idea to catch all sorts of exceptions in your code and suppress them as soon as possible; let me warn you that this is not a good idea. A good programmer catches an exception in code only if he answers yes to one or more of the following questions: á Will I attempt to recover from this error in the catch block? á Will I log the exception information in a system event log or another log file? á Will I add relevant information to the exception and rethrow it? á Will I execute cleanup code that must run even if an exception occurs? If you answered no to all these questions, you should not catch the exception but rather just let it go. In that case, the exception propagates up to the calling code, and the calling code might have a better idea of how to handle the exception. FIGURE 4.4 To get information about an exception, catch the exception object and access its Message property. TIP EXAM CLS and Non-CLS Compliant Exceptions All languages that follow the Common Language Specification (CLS) throw exceptions of type System.Exception or a type that derives from System.Exception. A non-cls compliant language might throw exceptions of other types, too. You can catch those types of exceptions by placing a general catch block (one that does not specify any exception) with a try block. In fact, a general catch block can catch exceptions of all types so it is the most generic of all catch blocks. This means that the general catch block should be the last catch block among the multiple catch blocks associated with a try block.

12 CH04 4/7/03 11:03 AM Page Part I DEVELOPING WEB APPLICATIONS NOTE checked and unchecked Keywords Visual C#.NET provides the checked and unchecked keywords, which can be used to enclose a block of statements (for example, checked a = c/d) or as an operator when you supply parameters enclosed in parentheses (for example, unchecked(c/d)). The checked keyword enforces checking of any arithmetic operation for overflow exceptions. If constant values are involved, they are checked for overflow at compile time. The unchecked keyword suppresses the overflow checking and instead of raising an OverflowException exception, the unchecked keyword returns a truncated value in case of overflow. If checked and unchecked are not used, the default behavior in C# is to raise an exception in case of overflow for a constant expression; it truncates the results in case of overflow for the non-constant expressions. The throw Statement A throw statement explicitly generates an exception in code. You use throw when a particular path in code results in an anomalous situation. You should not throw exceptions for anticipated cases such as users entering an invalid username or password; instead, you can handle this in a method that returns a value indicating whether the logon is successful. If you do not have the correct permissions to read records from the user table and you try to read those records, an exception is likely to occur because a method for validating users should normally have read access to the user table. Using exceptions to control the normal flow of execution adds two bad attributes to your code: á It might make your code difficult to read and maintain because the use of try-catch blocks to control the normal flow of execution forks the regular program logic between separate locations. á It might make your programs slow because exception handling consumes more resources (although not too many) than just returning values from a method. There are two ways you can use the throw statement. In its simplest form, you can just rethrow the exception in a catch block: catch(exception e) //TODO: Add code to create an entry in event log throw; This use of the throw statement rethrows the exception that was just caught. It can be useful in situations in which you do not want to handle the exception yourself but would like to take other actions (for example, recording the error in an event log or sending an notification about the error) when an exception occurs. Then you can pass the exception as is to its caller. The second way of using a throw statement is to use it to throw explicitly created exceptions; for example, string strmessage = EndDate should be greater than the StartDate ;

13 CH04 4/7/03 11:03 AM Page 293 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 293 ArgumentOutOfRangeException newexception = new ArgumentOutOfRangeException(strMessage); throw newexception; In this example, I first create a new instance of the ArgumentOutOfRangeException object and associate a custom error message with it, and then I throw the newly created exception. You are not required to put this usage of the throw statement inside a catch block because you are just creating and throwing a new exception rather than rethrowing an existing one. You typically use this technique to raise your own custom exceptions. I discuss how to do that later in this chapter. An alternative way of throwing an exception is to throw it after wrapping it with additional useful information; for example, catch(argumentnullexception ane) // TODO: Add code to create an entry in the log file string strmessage = CustomerID cannot be null ; ArgumentNullException newexception = new ArgumentNullException(strMessage, ane); throw newexception; You might need to catch an exception that you cannot handle completely. You would then perform any required processing and throw a more relevant and informative exception to the caller code so that it can perform the rest of the processing. In this case, you can create a new exception whose constructor wraps the previously caught exception in the new exception s InnerException property. The caller code then has more information available to handle the exception appropriately. It is interesting to note that because InnerException is of type Exception, it also has an InnerException property that might store a reference to another exception object. Therefore, when you throw an exception that stores a reference to another exception in its InnerException property, you are actually propagating a chain of exceptions. This information is very valuable at the time of debugging and allows you to trace down the path of the problem to its origin. TIP EXAM Custom Error Messages When you create an exception object, you should use the constructor that allows you to associate a custom error message rather than use the default constructor. The custom error message can pass specific information about the cause of the error, as well as a possible way to resolve it.

14 CH04 4/7/03 11:03 AM Page Part I DEVELOPING WEB APPLICATIONS The finally Block The finally block contains the code that always executes, whether or not any exception occurs. You will use the finally block to write cleanup code that maintains your application in a consistent state and preserves the external environment. For example, you can write code to close files, database connections, and related input/output (I/O) resources in a finally block. TIP EXAM No Code in Between try-catchfinally Blocks When you write try, catch, and finally blocks, they should be in immediate succession of each other. You cannot write any other code between the blocks, although compilers allow you to place comments between them. It is not necessary for a try block to have an associated finally block. However, if you do write a finally block, you cannot have more than one, and the finally block must appear after all the catch blocks. Step by Step 4.3 illustrates the use of a finally block. STEP BY STEP 4.3 Using a finally Block 1. Add a new Web form to the project. Name it StepByStep4_3.aspx. 2. Place two TextBox controls (txtfilename and txttext), three Label controls (one being lblmessage), and a Button control (btnsave) on the form s surface and arrange them as shown in Figure Switch to code view and add the following using directive: using System.IO; 4. Attach the Click event handler to the btnsave control and add the following code to handle the Click event handler: private void btnsave_click( object sender, System.EventArgs e) // StreamWriter writes characters to a stream StreamWriter sw = null; try sw = new C:\temp\ + txtfilename.text); // Attempt to write the textbox contents // in a file sw.write(txttext.text); // This line only executes if there were

15 CH04 4/7/03 11:03 AM Page 295 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 295 // no exceptions so far lblmessage.text = Contents written, without any exceptions + <br> ; //catches all CLS-compliant exceptions catch(exception ex) string msg = String.Format( Message: 0<br> Stack Trace:<br> 1, ex.message, ex.stacktrace); lblmessage.text = ex.gettype().tostring() + <br> + msg + <br> ; goto end; // finally block is always executed to make // sure that the resources get closed whether // or not the exception occurs. Even if there // is a goto (transfer-control) statement // in the catch or try block, // the finally block is first executed // before the control goes to the goto label. finally if (sw!= null) sw.close(); lblmessage.text += Finally block always executes + whether or not exception occurs + <br> ; end: lblmessage.text += Control is at label: end ; continued FIGURE 4.5 The code in the finally block always executes regardless of any exception in the try block.

16 CH04 4/7/03 11:03 AM Page Part I DEVELOPING WEB APPLICATIONS continues 5. Set the Web form as the start page for the project. 6. Run the project. You will see a Web form as shown in Figure 4.5. Enter a filename and some text. Watch the order of the messages. You will note that the message being displayed in the finally block is always displayed regardless of whether the code generates any exception or not. Also, note that the message displayed by the finally block appears prior to the message displayed by the end label. TIP EXAM NOTE The finally Block Always Executes If you have a finally block associated with a try block, the code in the finally block always executes whether an exception occurs or not. Throwing Exceptions from a finally Block Although it is perfectly legitimate to throw exceptions from a finally block, you should avoid doing so. The reason for this is that when you are processing a finally block, you might already have an unhandled exception waiting to be caught. Step by Step 4.3 creates the file at the C:\temp folder of the Web server. For this example to work, the ASP.NET process must have write permission on the c:\temp folder of the Web server. To assign the permissions, open the Web site using Windows explorer. Rightclick on the folder and select Properties, and then click on the Security tab. Click the Add Button and select the ASPNET user from the local computer. Click Add, and then OK. Click the check box to allow the user to write to the folder, and then click OK again. Step by Step 4.3 illustrates that the finally block always executes. In addition, if there is a transfer-control statement such as goto, break, or continue in either the try or the catch block, the control transfer happens only after the code in the finally block is executed. What happens if there is a transfer-control statement in the finally block as well? Well, that is not an issue because the Visual C#.NET compiler will not allow you to put a transfer-control statement such as goto inside a finally block. The finally block can be used in the form of a try-finally block without any catch block between them; for example, try // Write code to allocate some resources finally // Write code to Dispose all allocated resources

17 CH04 4/7/03 11:03 AM Page 297 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 297 This use ensures that allocated resources are properly disposed of, no matter what happens in the try block. In fact, Visual C#.NET provides a using statement that does exactly the same job but with less code to write. A typical use of the using statement is as follows: // Write code to allocate some resource // List the allocated resources in a // comma-separated list inside the // parentheses of the using block using(...) // use the allocated resource // Here, the Dispose method is called for all the // objects referenced in the parentheses of the using // statement without writing any additional code á An exception occurs when a program encounters any unexpected problem during normal execution. á The FCL provides two main types of exceptions, namely SystemException and ApplicationException. SystemException represents the exceptions thrown by the CLR, whereas ApplicationException represents the exceptions thrown by the applications. á The System.Exception class represents the base class for all CLS-compliant exceptions and provides the common functionality for exception handling. á The try block consists of code that might raise an exception. A try block cannot exist on its own. It should be immediately followed by one or more catch blocks or a finally block. á The catch block handles any exception raised by the code in the try block. The CLR looks for a matching catch block to handle the exception; this is the first catch block with either the exact same exception or any of the exception s base classes. á If multiple catch blocks are associated with a try block, the catch blocks should be arranged in order of specific-to-general exception types. á The throw statement is used to raise an exception. á The finally block is used to enclose code that needs to run regardless of whether the exception is raised. R E V I E W B R E A K

18 CH04 4/7/03 11:03 AM Page Part I DEVELOPING WEB APPLICATIONS CREATING AND USING CUSTOM EXCEPTIONS Implement error handling in the user interface. TIP EXAM Using ApplicationException as a Base Class for Custom Exceptions Although you can derive custom exception classes directly from the Exception class, Microsoft recommends that you derive custom exception classes from the ApplicationException class. In most cases, the.net Framework s built-in exception classes, combined with custom messages that you create when instantiating a new exception, should meet your exception handling requirements. However, in some cases, you might need exception types that are specific to the problem you are solving. The.NET Framework allows you to define custom exception classes. To keep your custom-defined exception class homogeneous with the.net exception-handling framework, Microsoft recommends that you consider the following when you design a custom exception class: á Create an exception class only if no exception class exists that satisfies your requirement. á Derive all programmer-defined exception classes from the System.ApplicationException class. á End the name of custom exception classes with the word Exception, for example, MyOwnCustomException. á Implement three constructors with the signatures shown in the following code: public class MyOwnCustomException : ApplicationException // Default constructor public MyOwnCustomException () // Constructor accepting a single string message public MyOwnCustomException (string message) : base(message) // Constructor accepting a string message // and an inner exception that will be // wrapped by this custom exception class public MyOwnCustomException(string message, Exception inner) : base(message, inner)

19 CH04 4/7/03 11:03 AM Page 299 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 299 Step by Step 4.4 shows you how to create and use a custom exception. STEP BY STEP 4.4 Creating and Using a Custom Exception 1. Add a new Web form to the project. Name it StepByStep4_4.aspx. 2. Place two Label controls (one being lblresult), a TextBox control (txtdate), and the Button control (btnisleap), as shown in Figure Switch to the code view and, at the end of the class definition of StepByStep4_4, add the following definition for the MyOwnInvalidDateFormatException class: // You can create your own exception classes by // deriving from the ApplicationException class // It is good coding practice to end the class name // of the custom exception with the word Exception public class MyOwnInvalidDateFormatException : ApplicationException // It is a good practice to implement the three // recommended common constructors as shown here. public MyOwnInvalidDateFormatException() public MyOwnInvalidDateFormatException( string message): base(message) this.helplink = file://myowninvaliddateformatexceptionhelp.htm ; public MyOwnInvalidDateFormatException( string message, Exception inner): base(message, inner) 4. Add the following definition for the Date class: // This class does elementary date handling required // for this program public class Date FIGURE 4.6 Leap Year Finder implements a custom exception for invalid date format. continued

20 CH04 4/7/03 11:03 AM Page Part I DEVELOPING WEB APPLICATIONS continues private int day, month, year; public Date(string strdate) if (strdate.trim().length == 10) // Input data might be in an invalid // format, in which case // Convert.ToDateTime() method will fail try DateTime dt = Convert.ToDateTime(strDate); day = dt.day; month = dt.month; year = dt.year; // Catch the exception, attach that to the // custom exception, and throw the // custom exception catch(exception e) throw new MyOwnInvalidDateFormatException( Custom Exception Says: + Invalid Date Format, e); else // Throw the custom exception throw new MyOwnInvalidDateFormatException( The input does not match the + required format: MM/DD/YYYY ); // Find if the given date belongs to a leap year public bool IsLeapYear() return (year%4==0) && ((year %100!=0) (year %400 ==0)); 5. Add the following event handler for the Click event of btnisleap: private void BtnIsLeap_Click( object sender, System.EventArgs e) try Date dt = new Date(txtDate.Text); if (dt.isleapyear()) lblresult.text = This date is in a leap year ;

21 CH04 4/7/03 11:03 AM Page 301 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 301 else lblresult.text = This date is NOT in a leap year ; // Catch the custom exception and // display an appropriate message catch (MyOwnInvalidDateFormatException dte) string msg; // If some other exception was also // attached with this exception if (dte.innerexception!= null) msg = String.Format( Message:<br> 0<br><br> + Inner Exception:<br> 1, dte.message, dte.innerexception.message); else msg = String.Format( Message:<br> 0<br><br> + Help Link:<br> 1, dte.message, dte.helplink); lblresult.text = dte.gettype().tostring() + <br> + msg; 6. Set the Web form as the start page for the project. 7. Run the project. Enter a date and click the button. If the date you enter is in the required format, you see a result displayed in the Web page; otherwise, you get an error message in the Web page, as in Figure 4.7. FIGURE 4.7 The.NET Framework allows you to define custom exceptions. GUIDED PRACTICE EXERCISE 4.1 In this exercise, you create a custom-defined exception class that helps you implement custom error messages and custom error handling in your programs. You must create a keyword-searching page. The Web page should ask the user to enter some text in a multiline textbox and a keyword, and then search for the keyword in the text of the multiline textbox. The Web page should then display the number of lines containing the keyword. The Web page assumes that the entered keyword is a single word. If it is not a single word, you need to create and throw a custom exception for that case.

22 CH04 4/7/03 11:04 AM Page Part I DEVELOPING WEB APPLICATIONS How would you throw a custom exception to implement custom error messages and custom error handling in your program? You should try working through this problem on your own first. If you get stuck, or if you d like to see one possible solution, follow these steps: 1. Add a new Web form to your Visual C#.NET Project. Name the form GuidedPracticeExercise4_1.aspx. 2. Place and arrange the controls on the form as shown in Figure 4.8. Name the TextBox for setting the text to be searched as txttext. Set the TextMode property of txttext to MultiLine. Name the TextBox for setting the keyword as txtkeyword and the search button as btnsearch. FIGURE 4.8 The Keyword searching Web form throws a custom exception if the input is not in required format. 3. Create a new class named BadKeywordFormatException that derives from ApplicationException and place the following code inside it: public class BadKeywordFormatException : ApplicationException public BadKeywordFormatException() public BadKeywordFormatException( string message): base(message) public BadKeywordFormatException(string message, Exception inner): base(message, inner)

23 CH04 4/7/03 11:04 AM Page 303 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE Create a method named GetKeywordFrequency() in GuidedPracticeExercise4_1 class. This method returns the number of lines containing the keyword. Add the following code to the method: private int GetKeywordFrequency() if(this.txtkeyword.text.trim().indexof( ) >= 0) throw new BadKeywordFormatException( The keyword must be a single word ); int count = 0; String text = txttext.text; String[] line = txttext.text.split(); for (int inti=0; inti < line.length; inti++) if(line[inti].indexof(txtkeyword.text) >=0) count ++; return count; 5. Add the following code to the Click event handler of btnsearch: private void btnsearch_click( object sender, System.EventArgs e) if (txtkeyword.text.trim().length == 0) lblresult.text = Please enter a keyword to search ; return; else if(txttext.text.trim().length == 0) lblresult.text = Please enter text to search for keyword ; return; try lblresult.text = String.Format( The keyword: 0, was found in 1 lines, txtkeyword.text, GetKeywordFrequency()); catch(badkeywordformatexception bkfe) string msg = String.Format( Message:<br> 0<br><br> StackTrace:<br>1, bkfe.message, bkfe.stacktrace); lblresult.text = msg + <br> + bkfe.gettype().tostring(); catch(exception ex)

24 CH04 4/7/03 11:04 AM Page Part I DEVELOPING WEB APPLICATIONS string msg = String.Format( Message:<br> 0<br><br> StackTrace:<br>1, ex.message, ex.stacktrace); lblresult.text = msg + <br> + ex.gettype().tostring(); 6. Set the Web form as the start page for the project. 7. Run the project. Enter some text as well as the keyword to search for, and click the Search button. If the keyword entered is in the wrong format (that is, it contains two words), a custom exception is raised. If you have difficulty following this exercise, review the sections Handling Exceptions and Creating and Using Custom Exceptions earlier in this chapter. Perform Step by Steps 4.2 and 4.4. After doing this review, try this exercise again. MANAGING UNHANDLED EXCEPTIONS Implement error handling in the user interface. Configure custom error pages. Implement Global.asax, application, page-level, and page event error handling. The unhandled exceptions are those exceptions that are not caught in a try-catch block (inline coding) in an application. Whenever an unhandled exception occurs, ASP.NET displays its default error page to the user. The default page is not pretty and sometimes (depending on the settings in the web.config file) can provide error details, along with code that can be a major security concern. You re usually better off displaying your own custom error messages instead. ASP.NET stops processing the Web page after it encounters an unhandled exception. However, you can trap an unhandled exception at an object level such as Page or Application.

25 CH04 4/7/03 11:04 AM Page 305 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 305 Using Custom Error Pages Custom error pages are Web pages that are displayed in the browser whenever an unhandled exception occurs. You can even display custom error pages whenever an HTTP error occurs (such as Page Not Found, Internal Server Error, and so on) while requesting a Web page from an ASP.NET application. ASP.NET provides full built-in support to configure custom error pages in a Web application. This configuration information is stored in an XML-based configuration file (web.config) where you use the <customerrors> element to configure custom error pages. The <customerrors> element consists of two attributes mode and defaultredirect. The mode attribute specifies how the custom error pages should be displayed. It can have one of the following three values: á On Display custom error pages at both the local and remote clients. á Off Disable custom error pages at both the local and remote clients. á RemoteOnly Display custom error pages only at remote clients. For the local machine, display the default ASP.NET error pages. This is the default setting in the web.config file. defaultredirect is an optional attribute that specifies the custom error page to be displayed when an error occurs. You can either display a static page, such as HTML, or a dynamic page, such as ASPX, as a custom error page. When the defaultredirect attribute is not set to a custom error page, the ASP.NET displays a generic error message in the browser. A specific custom error page can be displayed for a specific HTTP error code by associating the error code with the Web page through the <error> element. Multiple <error> elements can be nested inside the <customerrors> element. The <error> element consist of the following two attributes: á statuscode HTTP error status code. For example: 403 (Forbidden), 404 (Not Found), 500 (Internal Server Error), and so on. á redirect The error page to which the browser should be redirected when the associated HTTP error occurs.

26 CH04 4/7/03 11:04 AM Page Part I DEVELOPING WEB APPLICATIONS TIP EXAM Configuring Custom Error Pages Through IIS An alternative way of configuring custom error pages is through Internet Information Services (IIS). When given a choice between IIS and ASP.NET custom error pages, you might prefer ASP.NET, because in ASP.NET the custom pages are configured in an XML-based web.config (application configuration) file, resulting in easy (xcopy) deployment and management. If an error occurs that has no specific page assigned through the <error> element, the custom error page specified by the defaultredirect attribute of the <customerrors> element is displayed. STEP BY STEP 4.5 Setting Custom Error Pages for a Web Application 1. Open the web.config file from the Solution Explorer. Search for the <customerrors> element in the file. Modify the <customerrors> element with the following code in the file: <customerrors mode= On defaultredirect= ApplicationError.htm > <error statuscode= 403 redirect= Forbidden.htm /> <error statuscode= 404 redirect= NotFound.htm /> </customerrors> 2. Select Project, Add HTML Page. This opens the Add New Item dialog box. Create the page with the name ApplicationError.htm. Switch to HTML view and modify it with the following HTML code: <!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 Transitional//EN > <HTML> <HEAD> <TITLE>Application Error</TITLE> <META NAME= GENERATOR Content= Microsoft Visual Studio 7.0 > </HEAD> <BODY> <h1>application Error</h1> <p>sorry there is a server application error, and we are unable to process your request.</p> </BODY> </HTML> 3. Select Project, Add HTML Page. This opens the Add New Item dialog box. Add one more page with the name Forbidden.htm. Switch to HTML view and modify it with the following HTML code: <!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 Transitional//EN > <HTML> <HEAD>

27 CH04 4/7/03 11:04 AM Page 307 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 307 <TITLE>Page Forbidden</TITLE> <META NAME= GENERATOR Content= Microsoft Visual Studio 7.0 > </HEAD> <BODY> <h1> Page Forbidden</h1> <p>sorry this page is forbidden, and we cannot fulfil your request.</p> </BODY> </HTML> 4. Select Project, Add HTML Page. This opens the Add New Item dialog box. Add another page with the name NotFound.htm. Switch to HTML view and modify it with the following HTML code: <!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 Transitional//EN > <HTML> <HEAD> <TITLE>Page Not Found</TITLE> <META NAME= GENERATOR Content= Microsoft Visual Studio 7.0 > </HEAD> <BODY> <H1>Page Not Found</H1> <p>sorry we don t have the page you requested. </p> </BODY> </HTML> 5. Set StepByStep4_1.aspx as the start page for the project. 6. Run the project. Enter invalid values for miles and gallons and click the Calculate button. The ApplicationError.htm page is displayed. The Web page StepByStep4_1.aspx has no inline coding to handle exceptions, and it throws an unhandled exception. As a result, the custom error Web page is displayed as shown in Figure 4.9. continued FIGURE 4.9 Custom error pages can be displayed whenever an unhandled exception occurs.

28 CH04 4/7/03 11:04 AM Page Part I DEVELOPING WEB APPLICATIONS continues 7. Now try displaying the code-behind file of StepByStep4_1.aspx by typing (Substitute the name of your Web server for localhost if the Web server is not on your development computer.) You should see that this request generates an HTTP Page Forbidden (403) error. Because a different custom Web page is specified for HTTP error code 403, the PageForbidden.htm page is displayed as shown in Figure 4.10, rather than the default custom error page ApplicationError.htm. FIGURE 4.10 You can specify a specific custom error page for a specific HTTP error code. NOTE Forbidden Files The *.cs files contain the source code for the application. Other files, such as *.config, *.resx, *.asax, and so on, also contain sensitive information. If the user can request these files through the browser, the security and intellectual property of your application could be at risk. Fortunately, ASP.NET restricts the access to these files by generating an HTTP 403 Forbidden error. 8. Now, try displaying a non-existent page in the Web application. Say that we make a typo by typing a hyphen instead of an underscore symbol, such as localhost/315c04/stepbystep4-1.aspx. Notice that this request generates an HTTP Page Not Found (404) error. The custom error page is only displayed if the not found page is one that would have been processed by ASP.NET. For example, if you tried to get to StepByStep4-1.htm, you wouldn t see the custom error page because IIS would never call ASP.NET to process the request of the HTML page. Again, because a different custom Web page for HTTP error code 404 is specified, the PageNotFound.htm page is displayed, as shown in Figure 4.11, rather than the default custom error page ApplicationError.htm. FIGURE 4.11 The custom error page is only displayed if the page requested is processed by ASP.NET.

29 CH04 4/7/03 11:04 AM Page 309 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE Repeat steps 6, 7, and 8 after changing the value of the mode attribute (of the <customerrors> element in the web.config file) to Off (where no custom error pages will be displayed) and then RemoteOnly (where custom error pages will be displayed on remote machines and default errors on the local machine). Setting a Custom Error Page for a Specific Page Sometimes there might be a special need in which a particular Web page in an application wants to display its own error page. This can be done by setting the ErrorPage attribute of the Page directive or the ErrorPage property of the Page class to the desired custom error page. When the custom error page is set using this technique, it will overwrite the settings that apply to this Web page via the web.config file. Step by Step 4.6 shows how to set a custom error page for a specific Web page in a Web application. STEP BY STEP 4.6 Setting a Custom Error Page for a Specific Web Page 1. In Solution Explorer, right-click on StepByStep4_1.aspx and select Copy. Right-click on your project and select Paste. Rename the pasted Web form StepByStep4_6.aspx. Open the ASPX (HTML view) and CS files for the new Web form and change all references to StepByStep4_1 so that they refer to StepByStep4_6 instead. 2. Open the StepByStep4_6.aspx page in the HTML view. Add the ErrorPage= Error4_6.htm attribute to the Page directive: <%@ Page language= c# Codebehind= StepByStep4_6.aspx.cs AutoEventWireup= false Inherits= _315C04.StepByStep4_6 ErrorPage= Error4_6.htm %> continued

30 CH04 4/7/03 11:04 AM Page Part I DEVELOPING WEB APPLICATIONS continues 3. Select Project, Add Html Page. This will open the Add New Item dialog box. Create a page with the name Error4_6.htm. Switch to HTML view and modify it with the following HTML code: <!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 Transitional//EN > <HTML> <HEAD> <META NAME= GENERATOR Content= Microsoft Visual Studio 7.0 > <TITLE>Error in StepByStep4_6.aspx</TITLE> </HEAD> <BODY> <h1> Error in StepByStep4_6.aspx</h1> <p>sorry, there was an error while processing StepByStep4_1.aspx page. Please ensure that you enter numeric, greater than zero data in both input fields.</p> <p>please try again.</p> </BODY> </HTML> 4. Set StepByStep4_6.aspx as the start page for the project. 5. Run the project. Enter invalid values for miles and gallons and click the Calculate button. You will notice that the Error4_6.htm page is displayed as shown in Figure The ErrorPage attribute page overrides the setting for ApplicationError.htm defined in the web.config file. FIGURE 4.12 You can set the custom error page for an individual page by using the ErrorPage attribute of the Page directive. 6. Stop the project. Set the StepByStep4_1.aspx as the start page for the project. Enter invalid values for miles and gallons and click the Calculate button. You will notice that the custom error page set in the web.config file,

31 CH04 4/7/03 11:04 AM Page 311 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 311 ApplicationError.htm is displayed, as shown in Figure 4.9. This is because this page does not have an ErrorPage attribute set to any custom page. Using Error Events When an unhandled exception occurs in a Web application, the following events are fired in successive order: 1. Page.Error (page level event, handled by the Page_Error() event handler) 2. Application.Error (application level event, handled by the Application_Error() event handler) Both of these event handlers can be used to trap and work with unhandled exceptions. Using the Page.Error Event The Page_Error() event handler can be used to trap unhandled exceptions at a page level. Step by Step 4.7 shows how to handle unhandled exceptions in a page. STEP BY STEP 4.7 Handling Unhandled Exception in a Page 1. In the Solution Explorer, right-click on StepByStep4_1.aspx and select Copy. Right-click on your project and select Paste. Rename the pasted Web form StepByStep4_7.aspx. Open the ASPX (HTML view) and CS files for the new Web form and change all references to StepByStep4_1 so that they refer to StepByStep4_7 instead. 2. Switch to design view. Open the Properties Window, select the Page object (StepByStep4_7) in the drop-down list, and attach an Error event handler to the Page object. Add the following code in the event handler: continued

32 CH04 4/7/03 11:04 AM Page Part I DEVELOPING WEB APPLICATIONS continues private void Page_Error( object sender, System.EventArgs e) // Display error details // Get the last error on the Server // by calling GetLastError() method // Clear the error to flush the new response // and erase the default ASP.NET error page Response.Write( Error Details: <br> ); Response.Write( Server.GetLastError().Message + <br> ); Response.Write( Server.GetLastError().StackTrace + <br> ); Server.ClearError(); 3. Set the Web form as the start page for the project. 4. Run the project. Enter wrong values for miles and gallons and click the Calculate button. You will see the program displaying the error details in the Web page as shown in Figure FIGURE 4.13 You can handle an unhandled exception when the Error event of the Page is raised.

33 CH04 4/7/03 11:04 AM Page 313 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE 313 The Page_Error() event handler in the previous example displays the details of the unhandled exception. This is achieved by calling the HttpServerUtility object s GetLastError() method via the Server property. The method returns an Exception object that is a reference to the last exception that occurred on the server. The ClearError() method of the HttpServerUtility object clears the last exception and does not fire subsequent error events (for example, Application.Error) for the exception. For this reason, you will notice that the custom error page is not displayed even though there is an unhandled error. Also for the same reason, the default ASP.NET error page also is not displayed if no custom error page is configured. Using the Application.Error Event You can also choose to trap unhandled exceptions of the entire application in the Application.Error event. This event is handled by the Application_Error() event handler available in the ASP.NET application file, global.asax. Handling exceptions at the application level can be helpful if you are planning to handle the exceptions of all pages in a similar fashion. Handling the exceptions at the application level saves you from writing repetitive code in all the Web pages in an application. For example, if you want to take custom actions such as logging the exception related information for all Web pages, your best bet is to trap the unhandled exceptions at the application level. Logging exceptions is one of the best ways to keep track of exceptions generated. A log maintained over a period of time might help you analyze and find patterns that give you useful debugging information. There are several ways you can log the information related to an event: á System event log á Custom log files á Databases such as SQL Server 2000 á notifications Among these ways, the System event log offers you the most robust way of event logging because it requires minimum assumptions for logging the event. The other cases are not as fail-safe because your

34 CH04 4/7/03 11:04 AM Page Part I DEVELOPING WEB APPLICATIONS NOTE NOTE The EventLog Class I discuss the EventLog class in detail in Chapter 14, Maintaining and Supporting a Web Application. Please refer to Table 14.3 in Chapter 14 for the description of methods and properties of the EventLog class. Logging in a Web Farm In case of a Web farm, you might want to log all the errors centrally in a SQL Server database. To make the scheme failsafe, you might choose to log locally if the database is not available and transfer the log to the central database when it is available again. application might lose connectivity with a database, the SMTP service might be down, or you might have problems writing an entry in custom log file. The.NET Framework provides you access to the System event log through the EventLog class. Windows 2000 (and later versions) have three default logs Application, System, and Security. You can use the EventLog class to create custom event logs. These event logs can be easily viewed using the Windows Event Viewer utility. STEP BY STEP 4.8 Logging Unhandled Exceptions in the System Event Log 1. Open the global.asax file in code view from the Solution explorer. 2. Add the following code in the Application_Error() event handler: protected void Application_Error( Object sender, EventArgs e) // Get the Exception object wrapped // in the InnerException property Exception unhandledexception = (Exception)Server.GetLastError().InnerException; //If no event source exist, create an event source if(!eventlog.sourceexists( Mileage Efficiency Calculator )) EventLog.CreateEventSource( Mileage Efficiency Calculator, Mileage Efficiency Calculator Log ); // Create an EventLog instance and // assign its source. EventLog eventlog = new EventLog(); eventlog.source = Mileage Efficiency Calculator ; string type= unhandledexception.message; // Write an informational entry to the event log. eventlog.writeentry(unhandledexception.message); Response.Write( An exception occurred: + Created an entry in the event log ); Server.ClearError();

35 CH04 4/7/03 11:04 AM Page 315 Chapter 4 ERROR HANDLING FOR THE USER INTERFACE Set the form StepByStep4_1.aspx as the start page for the project. 4. Run the project. You will notice that when you enter invalid values, you get a message saying that an entry is being created in the event log. Thus, unhandled exceptions of all Web pages of an application are handled by the Application_Error() event handler in the global.asax file. 5. Stop the Project. Set the form StepByStep4_7.aspx as the start page for the project. 6. Run the project. You will notice that when you enter invalid values, you get the error details displayed in the browser but no message about an entry in the event log. Thus, only the Page_Error() event handler is being executed because the StepByStep4_7.aspx page calls the Server.ClearError() method to clear the error and thus prevents further firing of error events for the error. 7. Stop the project. Open the form StepByStep4_7.aspx in code view. Comment the following line in the Page_Error() event handler: Server.ClearError(); 8. Run the project. You will notice that when you enter invalid values, you get the error details displayed as in an earlier step along with a message saying that an entry is been created in the event log. Here, both the Page.Error and Application.Error events are fired. 9. You can view the logged messages by viewing Start, Programs, Administrative Tools, Event Viewer. The Event Viewer will display the Mileage Efficiency Calculator Log in the left pane of the window, as shown in Figure The right pane of the window shows the logged events. You can double-click the event to view the description and other properties of the event, as shown in Figure Stop the project.open the file global.asax in code view. Comment the following line in the Application_Error() event handler: Server.ClearError(); continued

36 CH04 4/7/03 11:04 AM Page Part I DEVELOPING WEB APPLICATIONS continues FIGURE 4.14 You can view messages logged to an event log using the Windows Event Viewer. 11. Run the project. You will notice that when you enter invalid values, you get the custom error page displayed in the browser. This happens because the error is not cleared although the exceptions are still logged in the system event log. When ASP.NET propagates the unhandled exception to the Application object (Application.Error event), the Exception object is wrapped in an HttpUnHandledException object. Therefore, to access the exception at the application level, you must access the Exception object s InnerException property. FIGURE 4.15 You can view event properties for a particular event to see the event related details. R E V I E W B R E A K á If the existing exception classes do not satisfy your exception handling requirements, you can create new exception classes that can be specific to your application by deriving from the ApplicationException class. á Custom error pages can be used to display user-friendly messages rather than the default error page shown by ASP.NET. They can be set by configuring the <customerrors> element in the web.config file for all the Web pages in an application.

12/14/2016. Errors. Debugging and Error Handling. Run-Time Errors. Debugging in C# Debugging in C# (continued)

12/14/2016. Errors. Debugging and Error Handling. Run-Time Errors. Debugging in C# Debugging in C# (continued) Debugging and Error Handling Debugging methods available in the ID Error-handling techniques available in C# Errors Visual Studio IDE reports errors as soon as it is able to detect a problem Error message

More information

Question And Answer.

Question And Answer. Q.1 Which type of of the following code will throw? Using System; Using system.io; Class program Static void Main() Try //Read in non-existent file. Using (StreamReader reader = new StreamReader(^aEURoeI-Am

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception

More information

Debugging and Handling Exceptions

Debugging and Handling Exceptions 12 Debugging and Handling Exceptions C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 1 4th Edition Chapter Objectives Learn about exceptions,

More information

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES 1 2 13 Exception Handling It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something. Franklin Delano Roosevelt O throw away the worser

More information

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms; Lecture #13 Introduction Exception Handling The C++ language provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. Exceptions

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

Handle Web Application Errors

Handle Web Application Errors Handle Web Application Errors Lesson Overview In this lesson, you will learn about: Hypertext Transfer Protocol (HTTP) error trapping Common HTTP errors HTTP Error Trapping Error handling in Web applications

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166 Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 7 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 7 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Essential

More information

After completing this appendix, you will be able to:

After completing this appendix, you will be able to: 1418835463_AppendixA.qxd 5/22/06 02:31 PM Page 879 A P P E N D I X A A DEBUGGING After completing this appendix, you will be able to: Describe the types of programming errors Trace statement execution

More information

Exception-Handling Overview

Exception-Handling Overview م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the

More information

Exception/Error Handling in ASP.Net

Exception/Error Handling in ASP.Net Exception/Error Handling in ASP.Net Introduction Guys, this is not first time when something is written for exceptions and error handling in the web. There are enormous articles written earlier for this

More information

Error Handling. Exceptions

Error Handling. Exceptions Error Handling Exceptions Error Handling in.net Old way (Win32 API and COM): MyFunction() error_1 = dosomething(); if (error_1) display error else continue processing if (error_2) display error else continue

More information

6.Introducing Classes 9. Exceptions

6.Introducing Classes 9. Exceptions 6.Introducing Classes 9. Exceptions Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Learning

More information

Name: Class: Date: 2. Today, a bug refers to any sort of problem in the design and operation of a program.

Name: Class: Date: 2. Today, a bug refers to any sort of problem in the design and operation of a program. Name: Class: Date: Chapter 6 Test Bank True/False Indicate whether the statement is true or false. 1. You might be able to write statements using the correct syntax, but be unable to construct an entire,

More information

11Debugging and Handling. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

11Debugging and Handling. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies 11Debugging and Handling 11Exceptions C# Programming: From Problem Analysis to Program Design 2nd Edition David McDonald, Ph.D. Director of Emerging Technologies Chapter Objectives Learn about exceptions,

More information

Designing Robust Classes

Designing Robust Classes Designing Robust Classes Learning Goals You must be able to:! specify a robust data abstraction! implement a robust class! design robust software! use Java exceptions Specifications and Implementations

More information

Online Activity: Debugging and Error Handling

Online Activity: Debugging and Error Handling Online Activity: Debugging and Error Handling In this activity, you are to carry a number of exercises that introduce you to the world of debugging and error handling in ASP.NET using C#. Copy the application

More information

3. You are writing code for a business application by using C#. You write the following statement to declare an array:

3. You are writing code for a business application by using C#. You write the following statement to declare an array: Lesson 1: Introduction to Programming 1. You need to gain a better understanding of the solution before writing the program. You decide to develop an algorithm that lists all necessary steps to perform

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Exception Handling in C++

Exception Handling in C++ Exception Handling in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

MCAD/MCSD Developing and Implementing Web Applications with Visual Basic.NET and Visual Studio.NET Training Guide: Exam

MCAD/MCSD Developing and Implementing Web Applications with Visual Basic.NET and Visual Studio.NET Training Guide: Exam MCAD/MCSD Developing and Implementing Web Applications with Visual Basic.NET and Visual Studio.NET Training Guide: Exam 70-305 Copyright 2003 by Que Publishing International Standard Book Number: 0789728184

More information

Exceptions. Examples of code which shows the syntax and all that

Exceptions. Examples of code which shows the syntax and all that Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces

More information

16-Dec-10. Consider the following method:

16-Dec-10. Consider the following method: Boaz Kantor Introduction to Computer Science IDC Herzliya Exception is a class. Java comes with many, we can write our own. The Exception objects, along with some Java-specific structures, allow us to

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Sri Vidya College of Engineering & Technology Question Bank

Sri Vidya College of Engineering & Technology Question Bank 1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Bh Solution Sheet 4 Software Engineering in Java This is a solution set for CS1Bh Question Sheet 4. You should only consult these solutions after attempting the exercises. Notice that the solutions

More information

ASSERTIONS AND LOGGING

ASSERTIONS AND LOGGING SUMMARY Exception handling, ASSERTIONS AND LOGGING PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 2016 rcardin@math.unipd.it

More information

17. Handling Runtime Problems

17. Handling Runtime Problems Handling Runtime Problems 17.1 17. Handling Runtime Problems What are exceptions? Using the try structure Creating your own exceptions Methods that throw exceptions SKILLBUILDERS Handling Runtime Problems

More information

Checked and Unchecked Exceptions in Java

Checked and Unchecked Exceptions in Java Checked and Unchecked Exceptions in Java Introduction In this article from my free Java 8 course, I will introduce you to Checked and Unchecked Exceptions in Java. Handling exceptions is the process by

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

C#: framework overview and in-the-small features

C#: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer C#: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Chapter 13 Exception Handling

Chapter 13 Exception Handling Chapter 13 Exception Handling 1 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.1) Exception Handling 1 Outline Exception Handling Mechanisms Exception handling fundamentals Exception Types Uncaught exceptions Try and catch Multiple catch

More information

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 14: Exceptions 10:00 AM, Feb 26, 2018 Contents 1 Exceptions and How They Work 1 1.1 Update to the Banking Example.............................

More information

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved. Chapter 9 Exception Handling Copyright 2016 Pearson Inc. All rights reserved. Last modified 2015-10-02 by C Hoang 9-2 Introduction to Exception Handling Sometimes the best outcome can be when nothing unusual

More information

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions CS112 Lecture: Exceptions Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions Materials: 1. Online Java documentation to project 2. ExceptionDemo.java to

More information

Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 2012

Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 2012 Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 2012 1 Objective To understand why exceptions are useful and why Visual Basic has them To gain experience with exceptions and exception

More information

Working with Data in ASP.NET 2.0 :: Handling BLL and DAL Level Exceptions Introduction

Working with Data in ASP.NET 2.0 :: Handling BLL and DAL Level Exceptions Introduction 1 of 9 This tutorial is part of a set. Find out more about data access with ASP.NET in the Working with Data in ASP.NET 2.0 section of the ASP.NET site at http://www.asp.net/learn/dataaccess/default.aspx.

More information

! Errors can be dealt with at place error occurs

! Errors can be dealt with at place error occurs UCLA Stat 1D Statistical Computing and Visualization in C++ Instructor: Ivo Dinov, Asst. Prof. in Statistics / Neurology University of California, Los Angeles, Winter 200 http://www.stat.ucla.edu/~dinov/courses_students.html

More information

CS 251 Intermediate Programming Exceptions

CS 251 Intermediate Programming Exceptions CS 251 Intermediate Programming Exceptions Brooke Chenoweth University of New Mexico Fall 2018 Expecting the Unexpected Most of the time our programs behave well, however sometimes unexpected things happen.

More information

CS112 Lecture: Exceptions and Assertions

CS112 Lecture: Exceptions and Assertions Objectives: CS112 Lecture: Exceptions and Assertions 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions 3. Introduce assertions Materials: 1. Online Java documentation

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

11 Coding Standards CERTIFICATION OBJECTIVES. Use Sun Java Coding Standards

11 Coding Standards CERTIFICATION OBJECTIVES. Use Sun Java Coding Standards 11 Coding Standards CERTIFICATION OBJECTIVES Use Sun Java Coding Standards 2 Chapter 11: Coding Standards CERTIFICATION OBJECTIVE Use Sun Java Coding Standards Spacing Standards The Developer exam is challenging.

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 8 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 4 is out and due on Tuesday Bugs and Exception handling 2 Bugs... often use the word bug when there

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 9 Date:

More information

CS 221 Review. Mason Vail

CS 221 Review. Mason Vail CS 221 Review Mason Vail Inheritance (1) Every class - except the Object class - directly inherits from one parent class. Object is the only class with no parent. If a class does not declare a parent using

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

BlueTeam Release Notes:

BlueTeam Release Notes: BlueTeam Release Notes: BlueTeam version 4.1.10 1. Incidents routed form IAPro to BlueTeam will carry the sender notes to the yellow sticky note available when the BT user opens the incident. 2. Added

More information

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/

More information

EXAM Microsoft MTA Software Development Fundamentals. Buy Full Product.

EXAM Microsoft MTA Software Development Fundamentals. Buy Full Product. Microsoft EXAM - 98-361 Microsoft MTA Software Development Fundamentals Buy Full Product http://www.examskey.com/98-361.html Examskey Microsoft 98-361 exam demo product is here for you to test the quality

More information

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar Exceptions Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

CATCH Me if You Can Doug Hennig

CATCH Me if You Can Doug Hennig CATCH Me if You Can Doug Hennig VFP 8 has structured error handling, featuring the new TRY... CATCH... FINALLY... ENDTRY structure. This powerful new feature provides a third layer of error handling and

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Spring 2017 Exceptions and Assertions 1 Outline General concepts about dealing with errors and failures Assertions: what, why, how For things you believe

More information

mywbut.com Exception Handling

mywbut.com Exception Handling Exception Handling An exception is a run-time error. Proper handling of exceptions is an important programming issue. This is because exceptions can and do happen in practice and programs are generally

More information

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. CSE 142, Summer 2002 Computer Programming 1. Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»

More information

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1. Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented

More information

HOUR 4 Understanding Events

HOUR 4 Understanding Events HOUR 4 Understanding Events It s fairly easy to produce an attractive interface for an application using Visual Basic.NET s integrated design tools. You can create beautiful forms that have buttons to

More information

Building Web Sites Using the EPiServer Content Framework

Building Web Sites Using the EPiServer Content Framework Building Web Sites Using the EPiServer Content Framework Product version: 4.60 Document version: 1.0 Document creation date: 28-03-2006 Purpose A major part in the creation of a Web site using EPiServer

More information

It d really be nice if all the scripts you write work flawlessly each and

It d really be nice if all the scripts you write work flawlessly each and Bonus Chapter Handling Exceptions In This Chapter Addressing errors the old way Getting to know exceptions Doing something with an exception Generating your own exceptions It d really be nice if all the

More information

Abstract Classes, Exceptions

Abstract Classes, Exceptions CISC 370: Inheritance, Abstract Classes, Exceptions June 15, 1 2006 1 Review Quizzes Grades on CPM Conventions Class names are capitalized Object names/variables are lower case String.doStuff dostuff();

More information

Internal Classes and Exceptions

Internal Classes and Exceptions Internal Classes and Exceptions Object Orientated Programming in Java Benjamin Kenwright Outline Exceptions and Internal Classes Why exception handling makes your code more manageable and reliable Today

More information

Review sheet for Final Exam (List of objectives for this course)

Review sheet for Final Exam (List of objectives for this course) Review sheet for Final Exam (List of objectives for this course) Please be sure to see other review sheets for this semester Please be sure to review tests from this semester Week 1 Introduction Chapter

More information

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

CMSC131. Exceptions and Exception Handling. When things go wrong in a program, what should happen. CMSC131 Exceptions and Exception Handling When things go "wrong" in a program, what should happen. Go forward as if nothing is wrong? Try to handle what's going wrong? Pretend nothing bad happened? Crash

More information

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15 s Computer Science and Engineering College of Engineering The Ohio State University Lecture 15 Throwable Hierarchy extends implements Throwable Serializable Internal problems or resource exhaustion within

More information

INTRODUCTION TO.NET. Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.)

INTRODUCTION TO.NET. Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.) INTRODUCTION TO.NET Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.) CLR Architecture and Services The.Net Intermediate Language (IL) Just- In-

More information

Comp 249 Programming Methodology Chapter 9 Exception Handling

Comp 249 Programming Methodology Chapter 9 Exception Handling Comp 249 Programming Methodology Chapter 9 Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted,

More information

WA1278 Introduction to Java Using Eclipse

WA1278 Introduction to Java Using Eclipse Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java

More information

Visual Basic 2008 Anne Boehm

Visual Basic 2008 Anne Boehm TRAINING & REFERENCE murach s Visual Basic 2008 Anne Boehm (Chapter 3) Thanks for downloading this chapter from Murach s Visual Basic 2008. We hope it will show you how easy it is to learn from any Murach

More information

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1 Exceptions: An OO Way for Handling Errors Introduction Rarely does a program runs successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. Such

More information

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions Dan Pomerantz School of Computer Science 19 March 2012 Overloading operators in classes It is useful sometimes to define

More information

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations , 1 C#.Net VT 2009 Course Contents C# 6 hp approx. BizTalk 1,5 hp approx. No exam, but laborations Course contents Architecture Visual Studio Syntax Classes Forms Class Libraries Inheritance Other C# essentials

More information

Saikat Banerjee Page 1

Saikat Banerjee Page 1 1. What s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each

More information

Traditional Error Handling

Traditional Error Handling Exception Handling 1 Traditional Error Handling We have already covered several mechanisms for handling errors in C++. We ll quickly review them here. Returning Error Values One classic approach involves

More information

Exceptions and assertions

Exceptions and assertions Exceptions and assertions CSE 331 University of Washington Michael Ernst Failure causes Partial failure is inevitable Goal: prevent complete failure Structure your code to be reliable and understandable

More information

DOT NET Syllabus (6 Months)

DOT NET Syllabus (6 Months) DOT NET Syllabus (6 Months) THE COMMON LANGUAGE RUNTIME (C.L.R.) CLR Architecture and Services The.Net Intermediate Language (IL) Just- In- Time Compilation and CLS Disassembling.Net Application to IL

More information

Exceptions. What exceptional things might our programs run in to?

Exceptions. What exceptional things might our programs run in to? Exceptions What exceptional things might our programs run in to? Exceptions do occur Whenever we deal with programs, we deal with computers and users. Whenever we deal with computers, we know things don

More information

Exceptions. Why Exception Handling?

Exceptions. Why Exception Handling? Exceptions An exception is an object that stores information transmitted outside the normal return sequence. It is propagated back through calling stack until some function catches it. If no calling function

More information

What You Need to Use this Book

What You Need to Use this Book What You Need to Use this Book The following is the list of recommended system requirements for running the code in this book: Windows 2000 Professional or Windows XP Professional with IIS installed Visual

More information

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited Chapter 12 Exception Handling and Text IO Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations When a program runs into a runtime error,

More information

Std 12 Lesson-10 Exception Handling in Java ( 1

Std 12 Lesson-10 Exception Handling in Java (  1 Ch-10 : Exception Handling in Java 1) It is usually understood that a compiled program is error free and will always successfully. (a) complete (b) execute (c) perform (d) accomplish 2) In few cases a

More information

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

Object Oriented Programming Exception Handling

Object Oriented Programming Exception Handling Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of

More information

Introduction to Java. Handout-3a. cs402 - Spring

Introduction to Java. Handout-3a. cs402 - Spring Introduction to Java Handout-3a cs402 - Spring 2003 1 Exceptions The purpose of exceptions How to cause an exception (implicitely or explicitly) How to handle ( catch ) an exception within the method where

More information

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 6 : Abstraction Lecture Contents 2 Abstract classes Abstract methods Case study: Polymorphic processing Sealed methods & classes

More information

Errors and Exceptions

Errors and Exceptions Exceptions Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception isn t necessarily your fault trying

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Defensive Programming

Defensive Programming Defensive Programming Software Engineering CITS1220 Based on the Java1200 Lecture notes by Gordon Royle Lecture Outline Why program defensively? Encapsulation Access Restrictions Documentation Unchecked

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Introducing Databases

Introducing Databases 12 Introducing Databases WHAT YOU WILL LEARN IN THIS CHAPTER: What a database is and which databases are typically used with ASP.NET pages What SQL is, how it looks, and how you use it to manipulate data

More information

Exception Safe Coding

Exception Safe Coding Exception Safe Coding Dirk Hutter hutter@compeng.uni-frankfurt.de Prof. Dr. Volker Lindenstruth FIAS Frankfurt Institute for Advanced Studies Goethe-Universität Frankfurt am Main, Germany http://compeng.uni-frankfurt.de

More information

User Scripting April 14, 2018

User Scripting April 14, 2018 April 14, 2018 Copyright 2013, 2018, Oracle and/or its affiliates. All rights reserved. This software and related documentation are provided under a license agreement containing restrictions on use and

More information

Assertions and Exceptions Lecture 11 Fall 2005

Assertions and Exceptions Lecture 11 Fall 2005 Assertions and Exceptions 6.170 Lecture 11 Fall 2005 10.1. Introduction In this lecture, we ll look at Java s exception mechanism. As always, we ll focus more on design issues than the details of the language,

More information