Professional VB 2005 - 2006 phần 4

Chia sẻ: Hà Nguyễn Thúy Quỳnh | Ngày: | Loại File: PDF | Số trang:110

lượt xem

Professional VB 2005 - 2006 phần 4

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Nếu phương pháp này có một tài sản, bạn có thể khai báo nó như là một phần của giao diện bằng cách sử dụng từ khóa bất động sản: Bạn cũng có thể khai báo các sự kiện như là một phần của giao diện bằng cách sử dụng từ khóa sự kiệnĐể bao gồm một phương pháp như là một phần của giao diện của bạn, bạn chỉ đơn giản

Chủ đề:

Nội dung Text: Professional VB 2005 - 2006 phần 4

  1. Chapter 9 Global impo PDF Merge and Split Unregistered Version - System Wrox String System Integer String Text Text Web Book Figure 9-8 My The My keyword is a novel concept to quickly give you access to your application, your users, your resources, the computer, or the network on which the application resides. The My keyword has been referred to as a way of speed-dialing common but complicated resources that you need access to. Using the My keyword, you can quickly get access to a wide variety of items such as user details or specific settings of the requestor’s browser. Though not really considered a true namespace, the My object declarations that you make work the same as the .NET namespace structure you are used to working with. To give you an example, let’s first look at how you get at the user’s machine name using the traditional namespace structure: Environment.MachineName.ToString() For this example, you simply need to use the Environment class and use this namespace to get at the MachineName property. Now let’s look at how you would accomplish this same task using the new My keyword: My.Computer.Info.MachineName.ToString() As you are looking at this example, you might be wondering what the point is if the example, which is using My, is lengthier than the first example that just works off of the Environment namespace. Just remember that it really isn’t about the length of what you type to get access to specific classes, but instead is about a logical way to find often accessed resources without the need to spend too much time hunting them down. Would you have known to look in the Environment class to get the machine name of the user’s computer? Maybe, but maybe not. Using My.Computer.Info.MachineName.ToString() is a tremendously more logical approach, and once compiled, this namespace declaration will be set to work with the same class as previously without a performance hit. 298
  2. Namespaces If you type the My keyword in your Windows Forms application, you will notice that IntelliSense provides you with six items to work with — Application, Computer, Forms, Resources, User, and WebServices. Though this new keyword works best in the Windows Forms environment, there are still things that you can use in the Web Forms world. If you are working for a Web application, then you impo PDF Merge and Split Unregistered Version - will have three items off of the My keyword — Application, Computer, and User. Each of these is broken down in the following sections. My.Application The My.Application namespace gives you quick access to specific settings and points that deal with your overall application. The following table details the properties and methods of the My.Application namespace. Property/Method Description Returns the contextual information about the thread of ApplicationContext the Windows Forms application. Provides quick access to the assembly of the Windows AssemblyInfo Forms. You can get at assembly information such as version number, name, title, copyright information, and more. A method that allows you to change the culture of the ChangeCurrentCulture current application thread. A method that allows you to change the culture that is ChangeCurrentUICulture being used by the Resource Manager. Returns the current culture which is being used by the CurrentCulture current thread. Returns the current directory for the application. CurrentDirectory Returns the current culture that is being used by the CurrentUICulture Resource Manager. Returns an instance of the ApplicationDeployment Deployment object, which allows for programmatic access to the application’s ClickOnce features. Returns a Boolean value which indicates whether the IsNetworkDeployed application was distributed via the network using the ClickOnce feature. If True, then the application was deployed using ClickOnce — otherwise False. This property allows you to write to your application’s Log event log listeners. Allows access to properties of the main form (initial MainForm form) for the application. Table continued on following page 299
  3. Chapter 9 Property/Method Description Returns a FormCollection object, which allows access OpenForms impo PDF Merge and Split Unregistered to the properties of the forms which are currently open. Version - Allows you to programmatically assign the splash screen SplashScreen for the application. While there is much that can be accomplished using the My.Application namespace, for an example of its use, let’s focus on the use of the AssemblyInfo property. This property provides access to the information that is stored in the application’s AssemblyInfo.vb file as well as other details about the class file. In one of your applications, you can create a message box that is displayed using the following code: MessageBox.Show(“Company Name: “ & My.Application.AssemblyInfo.CompanyName & _ vbCrLf & _ “Description: “ & My.Application.AssemblyInfo.Description & vbCrLf & _ “Directory Path: “ & My.Application.AssemblyInfo.DirectoryPath & vbCrLf & _ “Copyright: “ & My.Application.AssemblyInfo.LegalCopyright & vbCrLf & _ “Trademark: “ & My.Application.AssemblyInfo.LegalTrademark & vbCrLf & _ “Name: “ & My.Application.AssemblyInfo.Name & vbCrLf & _ “Product Name: “ & My.Application.AssemblyInfo.ProductName & vbCrLf & _ “Title: “ & My.Application.AssemblyInfo.Title & vbCrLf & _ “Version: “ & My.Application.AssemblyInfo.Version.ToString()) From this example, you can see that we can get at quite a bit of information concerning the assembly of the application that is running. Running this code will produce a message box similar to the one shown in Figure 9-9. Figure 9-9 300
  4. Namespaces Another interesting property to look at from the My.Application namespace is the Log property. This property allows you to work with the log files for your application. For instance, you can easily write to the system’s Application Event Log by first changing the application’s app.config file to include the following: impo PDF Merge and Split Unregistered Version - Once the configuration file is in place, you can then record entries to the Application Event Log as illustrated here in the following simple example: Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load My.Application.Log.WriteEntry(“Entered Form1_Load”, _ TraceEventType.Information, 1) End Sub You could also just as easily use the WriteExceptionEntry method in addition to the WriteEntry method. After running this application and looking in the Event Viewer, you will see the event shown in Figure 9-10. The previous example showed how to write to the Application Event Log when working with the objects that write to the event logs. In addition to the Application Event Log, there is also a Security Event Log and a System Event Log. It is important to note that when using these objects, it is impossible to write to the Security Event Log, and it is only possible to write to the System Event Log if the application does it under either the Local System or Administrator accounts. 301
  5. Chapter 9 impo PDF Merge and Split Unregistered Version - Figure 9-10 In addition to writing to the Application Event Log, you can also just as easily write to a text file. Just as with writing to the Application Event Log, writing to a text file also means that you are going to need to make changes to the app.config file.
  6. Namespaces Version=8.0.1200.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” initializeData=”FileLogWriter” /> impo PDF Merge and Split Unregistered Version - Now with this app.config file in place, you simply need to run the same WriteEntry method as before. Though this time, in addition to writing the Application Event Log, the information will also be written to a new text file. You will find the text file at C:\Documents and Settings\[ username ]\ Application Data\[ AssemblyCompany ]\[ AssemblyProduct ]\[ Version ]. For instance, in my example, the log file was found at C:\Documents and Settings\Administrator\Application Data\ Wrox\Log Writer\\. In the .log file found, you will see a line such as: Microsoft.VisualBasic.MyServices.Log.WindowsFormsSource Information 1 Entered Form1_Load Though split here on two lines (due to the width of the paper for this book), you will find this informa- tion in a single line within the .log file. By default it is separated by tabs, but you can also change the delimiter yourself by adding a delimiter attribute to the FileLog section in the app.config file. This is: In addition to writing to event logs and text files, you can also write to XML files, console applications, and more. My.Computer The My.Computer namespace can be used to work with the parameters and details of the computer in which the application is running. The following table details the objects contained in this namespace. Property Description This object allows you to work with audio files from Audio your application. This includes starting, stopping, and looping audio files. This object allows you to read and write to the clipboard. Clipboard This allows for access to the system clock to get at GMT Clock and the local time of the computer that is running the application. You can also get at the tick count, which is the number of milliseconds that has elapsed since the computer was started. Table continued on following page 303
  7. Chapter 9 Property Description This object provides a large collection of properties and FileSystem impo PDF Merge and Split Unregistered methods that drives, Version - allow for programmatic access to folders, and files. This includes the ability to read, write, and delete items in the file system. This provides access to the computer’s details such as Info amount of memory, the operating system type, which assemblies are loaded, and the name of the computer itself. This object provides access to knowledge of which Keyboard keyboard keys are pressed by the end user. Also included is a single method, SendKeys, which allows you to send the pressed keys to the active form. This provides a handful of properties that allow for Mouse detection of the type of mouse installed, and provides such details as whether the left and right mouse buttons have been swapped, whether a mouse wheel exists, and details on how much to scroll when the user uses the wheel. This is a read-only property that provides access to the Name name of the computer. This object provides a single property and some methods Network to enable you to interact with the network to which the computer where the application is running is connected. With this object, you can use the IsAvailable property to first check that the computer is connected to a network. If this is positive, the Network object allows you to upload or download files, and ping the network. This object can provide notify one if there are available Ports ports as well as allowing for access to the ports. This object allows determination of which printers are Printers available to the application as well as provides the ability to define default printers and print items to any of the printers available. This object provides programmatic access to the registry Registry and the registry settings. Using the Registry object, you can determine if keys exist, determine values, change values, and delete keys. Provides the ability to work with one or more screens Screen which may be attached to the computer. 304
  8. Namespaces There is a lot to the My.Computer namespace, so it is impossible to touch upon most of it. For an example of using this namespace, let’s take a look at the FileSystem property. The FileSystem property allows for you to easily and logically access drives, directories, and files on the computer. impo PDF Merge and Split Unregistered Version - To illustrate the use of this property, first start off by creating a Windows Form with a DataGridView and a Button control. It should appear as shown in Figure 9-11. Figure 9-11 This little application will look in the user’s My Music folder and list all of the .wma files found therein. Once listed, the user of the application will be able to select one of the listed files, and after pressing the Play button, the file will be launched and played inside Microsoft’s Windows Media Player. The first step after getting the controls on the form in place is to make a reference to the Windows Media Player DLL. You will find this on the COM tab, and the location of the DLL is C:\WINDOWS\System32\ wmp.dll. This will give you an object called WMPLib in the References folder of your solution. You might be wondering why you would make a reference to a COM object in order to play a .wma file from your application instead of using the My.Computer.Audio namespace that is provided to you. The Audio property only allows for the playing of .wav files, because to play .wma, .mp3, and similar files, the user must have the proper codecs on his or her machine. These codecs are not part of the Windows OS, but are part of Windows Media Player. 305
  9. Chapter 9 Now that the reference to the wmp.dll is in place, let’s put some code in the Form1_Load event. Private Sub Form1_Load(ByVal sender As System.Object, _ impo PDF Merge and Split UnregisteredHandles MyBase.Load ByVal e As System.EventArgs) Version - For Each MusicFile As String _ In My.Computer.FileSystem.GetFiles _ (My.Computer.FileSystem.SpecialDirectories.MyMusic, True, “*.wma”) Dim MusicFileInfo As System.IO.FileInfo = _ My.Computer.FileSystem.GetFileInfo(MusicFile.ToString()) Me.DataGridView1.Rows.Add(MusicFileInfo.Directory.Parent.Name & _ “\” & MusicFileInfo.Directory.Name & “\” & MusicFileInfo.Name) Next End Sub In this example, the My.Computer.FileSystem.GetFiles method points to the My Music folder through the use of the SpecialDirectories property. This property allows for logical and easy access to folders such as Desktop, My Documents, My Pictures, Programs, and more. Though it is possible to use just this first parameter with the GetFiles method, this example makes further definitions. The second parameter defines the recurse value — which states whether the subfolders should be perused as well. By default, this is set to False, but it has been changed to True for this example. The last parameter defines the wildcard that should be used in searching for elements. In this case, the value of the wildcard is *.wma, which instructs the GetFile method to get only the files that are of type .wma. Once retrieved with the GetFile method, the retrieved file is then placed inside the DataGridView control, again using the My.Computer.FileSystem namespace to define the value of the item placed within the row. Once the Form1_Load event is in place, the last event to construct is the Button1_Click event. This is illustrated here: Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim MediaPlayer As New WMPLib.WindowsMediaPlayer MediaPlayer.openPlayer(My.Computer.FileSystem.SpecialDirectories.MyMusic & _ “\” & DataGridView1.SelectedCells.Item(0).Value) End Sub From this example, you can see that it is pretty simple to play one of the provided .wma files. It is as simple as creating an instance of the WMPLib.WindowsMediaPlayer object and using the openPlayer method, which takes as a parameter the location of the file to play. In this case, you are again using the SpecialDirectories property. The nice thing about using this property is that it could be more difficult to find the user’s My Music folder due to the username changing the actual location of the files that the application is looking for, but using the My namespace allows it to figure out the exact location of the items. When built and run, the application provides a list of available music files and allows you to easily select one for playing in the Media Player. This is illustrated in Figure 9-12. 306
  10. Namespaces impo PDF Merge and Split Unregistered Version - Figure 9-12 Though it would have been really cool if it were possible to play these types of files using the Audio property from the My.Computer namespace, it is still possible to use the My.Computer.Audio name- space for playing .wav files and system sounds. To play a system sound, you use the following construct: My.Computer.Audio.PlaySystemSound(SystemSounds.Beep) The system sounds in the SystemSounds enumeration include: Asterisk, Beep, Exclamation, Hand, and Question. My.Forms The My.Forms namespace is just a quick and logical way of getting at the properties and methods of the forms that are contained within your solution. For instance, to get at the first form in your solution (assuming that it’s named Form1), you use the following namespace construct: My.Form.Form1 To get at other forms, you simply change the namespace so that the name of the form that you are trying to access follows the Form keyword in the namespace construction. 307
  11. Chapter 9 My.Resources The My.Resources namespace is a tremendously easy way of getting at the resources stored in your impo PDF Merge andopen upUnregistered Version - solution, application. If you Split the MyResources.resx file from the My Projects folder in your you can easily create as many resources as you wish. As an example, I created a single String resource titled MyResourceString and gave it a value of St. Louis Rams. To access the resources that you create, you use the simple reference as shown here: My.Resources.MyResourceString.ToString() Using IntelliSense, you will find all of your created resources listed after you type the period after the My.Resources string. My.User The My.User namespace allows you to work with the IPrincipal interface. You can use the My.User namespace to figure out if the user is authenticated or not, what the user’s name is, and more. For instance, if you have a login form in your application, you could allow access to a particular form with code similar to the following: If (Not My.User.IsInRole(“Administrators”)) Then ‘ Code here End If You can also just as easily get at the user’s name with the following: My.User.Identity.Name As well, you can check if the user is authenticated by using: If My.User.Identity.IsAuthenticated Then ‘ Code here End If My.WebServices When not using the My.WebServices namespace, you access your Web Services references in a lengthier manner. The first step in either case is to make a Web reference to some remote XML Web service in your solution. These references will then appear in the Web References folder in Solution Explorer in Visual Studio 2005. Before the introduction of the My namespace, you would have accessed the values that the Web reference exposed in the following manner: Dim ws As New ReutersStocks.GetStockDetails Label1.Text = ws.GetLatestPrice.ToString() This works, but now with the My namespace, you can use the following construct: Label1.Text = My.WebServices.GetStockDetails.GetLatestPrice.ToString() 308
  12. Namespaces S ummar y The introduction of namespaces with the .NET Framework provides a powerful tool that helps to impo PDF Merge and the logical capabilities from their physical implementation. While there are differences in the abstract Split Unregistered Version - syntax of referencing objects from a namespace and referencing the same object from a COM-style component implementation, there are several similarities. This chapter introduced namespaces and their hierarchical structure, and demonstrated ❑ That namespace hierarchies are not related to class hierarchies ❑ How to review and add references to a project ❑ How to import and alias namespaces at the module level ❑ How to create custom namespaces ❑ How to use the new My namespace Namespaces play an important role in enterprise software development. The fact that namespaces allow you to separate the implementation of related functional objects, while retaining the ability to group these objects, improves the overall maintainability of your code. Everyone who has ever worked on a large project has been put in the situation where a fix to a component has been delayed because of the potential impact on other components in the same project. Regardless of the logical separation of components in the same project, developers who took part in the development process worried about testing. With totally separate implementations for related components, it is not only possible to alleviate this concern but also easier than ever before for a team of developers to work on different parts of the same project. 309
  13. impo PDF Merge and Split Unregistered Version -
  14. impo PDF Merge and Split Unregistered Version - E xception Handling and Debugging All professional-grade programs need to handle unexpected conditions. In programming languages before Microsoft .NET, this was often called error handling. Unexpected conditions generated error codes, which were trapped by programming logic that took appropriate action. The common language runtime in .NET does not generate error codes. When an unexpected condition occurs, the CLR creates a special object called an exception. This object contains properties and methods that describe the unexpected condition in detail and communicate various items of useful information about what went wrong. Because .NET deals with exceptions instead of errors, the term “error handling” is seldom used in the .NET world. Instead, now refer to exception handling. This term refers to the techniques used in .NET to detect exceptions and take appropriate action. In this chapter, we will cover how exception handling works in Visual Basic .NET (VB.NET). There are many improvements over pre-.NET versions of Visual Basic. This chapter will discuss the common language runtime (CLR) exception handler in detail and the programming methods that are most efficient in catching errors. Specifically, it will discuss: ❑ A brief review of error handling in Visual Basic 6 (VB6) ❑ The general principles behind exception handling ❑ The Try . . . Catch . . . Finally structure, the Exit Try statement, and nested Try structures ❑ The exception object’s methods and properties
  15. Chapter 10 ❑ Exception handling between managed and unmanaged code, and how VB.NET assists you in that area ❑ Capabilities in Visual Studio .NET to work with exceptions impo PDF Merge and Split Unregistered Version - ❑ Error and trace logging and how you can use these methods to obtain feedback on how your program is working You’ll begin with a quick review of error handling in previous versions of Visual Basic to use as a reference point. Then you will look at the new ways of handling exceptions in .NET. A Brief Review of Error Handling in VB6 For compatibility, Visual Basic .NET still supports the old-style syntax for error handling that was used in Visual Basic 6 and earlier versions. That means you can still use the syntax presented in this review. However, it is strongly recommended that you avoid using this old-style syntax in favor of the exception handling features that are native to .NET. The old-style syntax in VB6 was handed down from DOS versions of BASIC. The On Error construct was created in an era when line labels and GoTo statements were commonly used. Such error handling is difficult to use and has limited functionality compared to more modern alternatives. In VB6, a typical routine with error handling code looks like this: Private Function OpenFile(sFileName As String) As Boolean On Error GoTo ErrHandler: Open sFileName For Random As #1 OpenFile = True Exit Sub ErrHandler: Select Case Err.Number Case 53 ‘ File not found MessageBox.Show “File not found” Case Else MessageBox.Show “Other error” End Select OpenFile = False End Function The top of the routine points to a section of code called an error handler, which is usually placed at the bottom of the routine. The error handler gets control as soon as an error is detected in the routine, and it looks at the error number to see what to do. The error number is available as a property of the Err object, which is a globally available object that holds error information in VB6. If the error handler can take care of the error without breaking execution, it can resume execution with the line of code that generated the error ( Resume) or the one after that ( Resume Next) or at a particular location ( Resume {LineLabel}). 312
  16. Exception Handling and Debugging This structure becomes more complex if the error handling needs to vary in the routine. Multiple On Error GoTo statements must be used to send errors to various error handlers, like this: Private Function OpenFile(sFileName As String) As Boolean impo PDF Merge and Split Unregistered Version - On Error GoTo ErrHandler1 ‘ Do calculations here Dim i As Integer i = Len(sFileName) Dim j As Integer j = 100 \ i On Error GoTo ErrHandler2 Open sFileName For Random As #1 OpenFile = True Exit Function ErrHandler1: Select Case Err.Number Case 6 ‘ Overflow MessageBox.Show “Overflow” Case Else MessageBox.Show “Other error” End Select OpenFile = False Exit Function ErrHandler2: Select Case Err.Number Case 53 ‘ File not found MessageBox.Show “File not found” Case Else MessageBox.Show “Other error” End Select OpenFile = False End Function With this type of error handling, it is easy to get confused about what should happen under various conditions. You must change the error handling pointer as necessary or errors will be incorrectly processed. There is very little information available about the error during the process, except for the error number. You can’t tell, for example, the line number on which the error was generated without single-stepping through the code. Such logic can rapidly become convoluted and unmanageable. There’s a much better way to manage errors in VB.NET, called structured exception handling. The rest of this chapter will discuss this new way to work with code errors, and you will use the term structured exception handling throughout, except for the small sections that discuss compatibility with older error-handling techniques. 313
  17. Chapter 10 E xceptions in .NET .NET implements a systemwide, comprehensive approach to exception handling. As noted in the chapter impo PDF Mergethe concept ofUnregistered Version - a set of introduction, and Split an error is expanded to exceptions, which are objects that contain information relevant to the error. Such an object is an instance of a class that derives from a class named System.Exception. Important Properties and Methods of an Exception The Exception class has properties that contain useful information about the exception. Property Description A string indicating the link to help for this exception. HelpLink Returns the exception object reference to an inner (nested) InnerException exception. A string that contains a description of the error, suitable for Message displaying to users. A string containing the name of an object that generated the Source error. A read-only property that holds the stack trace as a text StackTrace string. The stack trace is a list of the pending method calls at the point that the exception was detected. That is, if MethodA called MethodB, and an exception occurred in MethodB, the stack trace would contain both MethodA and MethodB. A read-only string property that holds the method that TargetSite threw the exception. The two most important methods of the Exception class are: Method Description Returns the first exception in the chain GetBaseException Returns the error string, which might include as much ToString information as the error message, the inner exceptions, and the stack trace, depending on the error You will see these properties and methods used in the code examples given later, once you have covered the syntax for detecting and handling exceptions. 314
  18. Exception Handling and Debugging How Exceptions Differ from the Err Object in VB6 Because an exception contains all of the information needed about an error, structured exception handling impo PDF Merge and Split Unregistered Version - relevant information does not use error numbers and the Err object. The exception object contains all the about the error. However, where there is only one global Err object in VB6, there are many types of exception objects in VB.NET. For example, if a divide by zero is done in code, then an OverflowException is generated. There are several dozen types of exception classes in VB.NET, and in addition to using the ones that are available in the .NET Framework, you can inherit from a class called ApplicationException and then create your own exception classes (see Chapter 6 for a discussion of inheritance). In .NET, all exceptions inherit from System.Exception. Special-purpose exception classes can be found in many namespaces. The following table lists four representative examples of the classes that extend Exception: Namespace Class Description Generated when a call to an object System InvalidOperationException method is inappropriate because of the object’s state Results when there is not enough System OutOfMemoryException memory to carry out an operation Often caused by an attempt to read System.XML XmlException invalid XML Represents errors in ADO.NET System.Data DataException components There are literally dozens of exception classes scattered throughout the .NET Framework namespaces. It is common for an exception class to reside in a namespace with the classes that commonly generate the exception. For example, the DataException class is in System.Data, with the ADO.NET components that often generate a DataException instance. Having many types of exceptions in VB.NET enables different types of conditions to be trapped with different exception handlers. This is a major advance over VB6. The syntax to do that is discussed next. Structured-Exception-Handling K eywords in VB.NET Structured exception handling depends on several new keywords in VB.NET. They are: ❑ Try — Begin a section of code in which an exception might be generated from a code error. This section of code is often called a Try block. In some respects, this would be the equivalent of an On Error statement in VB6. However, unlike an On Error statement, a Try statement does not indicate where a trapped exception should be routed. Instead, the exception is automatically routed to a Catch statement (discussed next). 315
  19. Chapter 10 ❑ Catch — Begin an exception handler for a type of exception. One or more Catch code blocks come after a Try block, with each Catch block catching a different type of exception. When an exception is encountered in the Try block, the first Catch block that matches that type of exception will receive control. impo PDF Merge and Split Unregistered Version - A Catch statement is analogous to the line label used in a VB6 On Error statement, but the ability to route different types of exceptions to different Catch statements is a radical improvement over VB6. ❑ Finally — Contains code that runs when the Try block finishes normally, or if a Catch block receives control and then finishes. That is, the code in the Finally block always runs, regardless of whether an exception was detected. Typically, the Finally block is used to close or dispose of any resources, such as database connections, that might have been left unresolved by the code that had a problem. There is no equivalent of a Finally in VB6. ❑ Throw — Generate an exception. This is similar to Err.Raise in VB6. It’s usually done in a Catch block when the exception should be kicked back to a calling routine or in a routine that has itself detected an error such as a bad argument passed in. The Try, Catch, and Finally Keywords Here is an example showing some typical simple structured exception handling code in VB.NET. In this case, the most likely source of an error is the iItems argument. If it has a value of zero, this would lead to dividing by zero, which would generate an exception. First, create a Windows Application in Visual Basic 2005, and place a button on the default Form1 created in the project. In the button’s click event, place the following two lines of code: Dim sngAvg As Single sngAvg = GetAverage(0, 100) Then put the following function in the form’s code: Private Function GetAverage(iItems As Integer, iTotal As Integer) as Single ‘ Code that might throw an exception is wrapped in a Try block Try Dim sngAverage As Single ‘ This will cause an exception to be thrown if iItems = 0 sngAverage = CSng(iTotal \ iItems) ‘ This only executes if the line above generated no error MessageBox.Show(“Calculation successful”) Return sngAverage Catch excGeneric As Exception ‘ If the calculation failed, you get here MessageBox.Show(“Calculation unsuccessful - exception caught”) Return 0 End Try End Function 316
  20. Exception Handling and Debugging In this code, you are trapping all the exceptions with a single generic exception type, and you don’t have any Finally logic. Run the program, and press the button. You will be able to follow the sequence better if you place a breakpoint at the top of the GetAverage function and step through the lines. impo PDF Merge and Split Unregistered Version - Here is a more complex example that traps the divide-by-zero exception explicitly. This second version of the GetAverage function (notice that the name is GetAverage2) also includes a Finally block: Private Function GetAverage2(iItems As Integer, iTotal As Integer) as Single ‘ Code that might throw an exception is wrapped in a Try block Try Dim sngAverage As Single ‘ This will cause an exception to be thrown. sngAverage = CSng(iTotal \ iItems) ‘ This only executes if the line above generated no error. MessageBox.Show(“Calculation successful”) Return sngAverage Catch excDivideByZero As DivideByZeroException ‘ You’ll get here with an DivideByZeroException in the Try block MessageBox.Show(“Calculation generated DivideByZero Exception”) Return 0 Catch excGeneric As Exception ‘ You’ll get here when any exception is thrown and not caught in ‘ a previous Catch block. MessageBox.Show(“Calculation failed - generic exception caught”) Return 0 Finally ‘ Code in the Finally block will always run. MessageBox.Show(“You always get here, with or without an error”) End Try End Function In this code, there are two Catch blocks for different types of exceptions. If an exception is generated, .NET will go down the Catch blocks looking for a matching exception type. That means the Catch blocks should be arranged with specific types first and more generic types later. Place the code for GetAverage2 in the form, and place another button on Form1. In the Click event for the second button, place the code: Dim sngAvg As Single sngAvg = GetAverage2(0, 100) Run the program again and press the second button. As before, it’s easier to follow if you set a breakpoint early in the code and then step through the code line by line. 317



Đồng bộ tài khoản