Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning REALbasic - From Novice To Professional (2006)

.pdf
Скачиваний:
239
Добавлен:
17.08.2013
Размер:
18.51 Mб
Скачать

336

C H A P T E R 1 2 D E B U G G I N G R E A L B A S I C A P P L I C A T I O N S

REALbasic also lets you create Exception blocks that trap specific run-time errors, as the following example shows.

Dim strCustomerArray(2) As String

strCustomerArray(0) = "Molly" strCustomerArray(1) = "William" strCustomerArray(2) = "Alexander"

MsgBox strCustomerArray(5)

Exception err

If err IsA OutOfBoundsException Then

MsgBox "Something went wrong with the array"

Else

MsgBox "Unknown Error!"

End If

Note The previous example used the IsA operator to determine what type of run-time error occurred. The IsA operator returns a Boolean value of True when a match occurs.

In this example, the Exception block executes any time a run-time error occurs. Using the ErrorParameter, the Exception block executes an If…Then…Else block that processes the runtime error. One of two different error messages is then displayed based on whether an

OutOfBoundsException error occurs.

Note Refer to the REALbasic Language Reference for a complete list of run-time errors.

If you prefer, you could rework the previous example as the following shows, listing multiple Exception blocks in place of an If…Then…Else block.

Dim strCustomerArray(2) As String

strCustomerArray(0) = "Molly" strCustomerArray(1) = "William" strCustomerArray(2) = "Alexander"

MsgBox strCustomerArray(5)

Exception err As OutOfBoundsException

MsgBox "Something went wrong with with the array"

Tip

C H A P T E R 1 2 D E B U G G I N G R E A L B A S I C A P P L I C A T I O N S

337

Exception err As NilObjectException

MsgBox "Object does not exist"

Exception blocks provide you with the capability to recover from many different run-time errors. For them to be effective, however, you must anticipate the locations within your REALbasic application where they will be needed and take the appropriate actions.

Handling Run-Time Errors with Try Blocks

REALbasic also lets you trap and handle run-time errors using Try blocks, which have the following syntax.

Try

Code statements where errors may occur

Catch[ErrorParameter] [As ErrorType]

Code statements to execute

Finally

Code statements run whenever a run-time error occurs

End [Try]

To set up a Try block, you start by placing the Try keyword just before any code statements where run-time errors are likely to occur. Then, you add one or more Catch blocks following these code statements. You can add as many different Catch blocks as you want, each of which should trap a different type or error. If you choose, you can add an optional Finally block, which executes any time a run-time error is trapped by the Try block, regardless of whether a Catch block was executed.

The following example demonstrates how to set up a Try block to trap and handle runtime errors.

Dim strCustomerArray(2) As String

strCustomerArray(0) = "Molly" strCustomerArray(1) = "William" strCustomerArray(2) = "Alexander"

Try

MsgBox strCustomerArray(5)

Catch err As OutOfBoundsException

MsgBox "Something went wrong with the array"

End Try

The order in which you define Catch blocks within your Try blocks is important. REALbasic only executes the first matching Catch block it finds. So, when defining multiple Catch blocks, be sure to define them so the more specific Catch blocks occur before the more general ones.

338

C H A P T E R 1 2 D E B U G G I N G R E A L B A S I C A P P L I C A T I O N S

Building a Network Connection Checker Application

This chapter concludes by demonstrating how to create a small network connection utility that detects and displays information about every currently active network interface on a computer. To build this application, you need to learn how to work with properties and methods belonging to the System and NetworkInterface objects. In addition, you have the opportunity to put your newly acquired exception-handling experience to use.

Note The System object provides access to properties and methods that you can use to retrieve information about a computer. One System object property is the NetworkInterfaceCount property, which returns an Integer representing the number of network interface devices connected to a computer. The System object also provides access to the GetNetworkInterface method, which can be used to instantiate a NetworkInterface object, which can then be used to retrieve information about each network interface attached to the computer. Specifically, the NetworkInterface object provides access to the IPAddress, MacAddress, and SubnetMask properties, which return the IP address, Mac address, and Subnet Mask for a specified network interface.

The development of the Network Connection Checker is demonstrated here using the Windows version of REALbasic, although you can just as easily create this application using the Macintosh or Linux version of REALbasic. All the steps involved are the same. Figure 12-12 provides you with a look at the Network Connection Checker when it first starts.

Figure 12-12. The Network Connection Checker can be used to display information about every network interface currently set up on a computer, as seen on Windows.

C H A P T E R 1 2 D E B U G G I N G R E A L B A S I C A P P L I C A T I O N S

339

Setting Up the User Interface

The Network Connection Checker application is made up of a menu system and a single window that contains a ListBox, a PushButton, and three EditField controls, along with five StaticText controls used to label the other controls. To create this application, open a new REALbasic desktop application. Add the required controls to Window1 and align them as you saw in Figure 12-12. Next, modify the properties for the application’s window and controls, as shown in Table 12-1.

Table 12-1. Property Modifications for the Network Connection Checker Application

Object

Property

Value

Window1

Title

Network Connection Checker

ListBox1

Name

lbxInterfaceIDs

EditField1

Name

IPAddressField

EditField2

Name

SubnetMaskField

EditField3

Name

MACAddressField

PushButton1

Name

pbnRefresh

 

Caption

Refresh

StaticText1

Name

txtNetConnection

 

Text

Network Connection:

StaticText2

Name

txtIPAddress

 

Text

IP Address:

StaticText2

Name

txtSubnetMask

 

Text

Subnet Mask:

StaticText4

Name

MacAddressField

 

Text

MAC Address:

 

 

 

Now that Window1 and its controls are configured, let’s set up the application’s menu system. To do so, double-click the Menubar1 item located on the Projects screen. REALbasic responds by displaying the default menu system for the application in the MenuBar Editor. The application doesn’t need the default Edit menu, so delete it by selecting it and clicking Delete. This leaves only the File menu, which is all this application requires.

Adding Custom Properties and Methods

The event handlers for the window of the Network Connection Checker application (Window1) are where most of this application’s code will reside. Before you begin adding code to these event handlers, however, you need to add a property and two methods to the window. The property will be used to declare a variable representing an instance of the NetworkInterface object. Different event handlers use this property to retrieve network interface information.

340

C H A P T E R 1 2 D E B U G G I N G R E A L B A S I C A P P L I C A T I O N S

The two methods you create will be responsible for displaying network interface data and for refreshing the display of all active network interfaces.

To add the property, open the Code Editor for Window1. Next, click the Add Property button located on the Code Editor’s toolbar and then enter InterfaceID in the Declaration field and NetworkInterface in the As field.

To add the first custom method, click the Add Method button located on the Code Editor’s toolbar. A method declaration area is displayed at the top of the Code Editor. Enter GetNetworkInfo in the Method Name field and add the following programming statements to the subroutine.

'Display the IP Address of the currently selected network interface IPAddressField.Text = InterfaceID.IPAddress

'Display the Subnet Mask of the currently selected network interface SubnetMaskField.Text = InterfaceID.SubnetMask

'Display the MAC Address of the currently selected network interface MacAddressField.Text = InterfaceID.MACAddress

When called, this subroutine is responsible for updating the display of IP Address, Subnet Mask and MAC Address information for the currently selected network interface device (as specified by InterfaceID property).

To add the second custom method, click the Add Method button again, and then enter RefreshDisplay in the Method Name field. Next, add the following programming statements to the subroutine.

'Declare a variable to be used as a counter Dim intCounter As Integer

'Delete any data stored in the ListBox control lbxInterfaceIDs.DeleteAllRows

'Set up a loop to process all network interfaces found on the computer For intCounter = 0 To System.NetworkInterfaceCount - 1

lbxInterfaceIDs.AddRow Str(intCounter) 'Add a network interface

Next

'Set the Network Interface ID equal to zero InterfaceID = System.GetNetworkInterface(0)

GetNetworkInfo() 'Call subroutine that displays network interface data

Exception err 'Trap exceptions

C H A P T E R 1 2 D E B U G G I N G R E A L B A S I C A P P L I C A T I O N S

341

'Exception handler for OutofBoundsException errors If err IsA OutOfBoundsException Then

'Clear out data displayed in EditField controls displayed on the window IPAddressField.Text = ""

SubnetMaskField.Text = ""

MacAddressField.Text = ""

'Display a user friendly error message

MsgBox "There are no currently active network connections."

End If

As the embedded comments document, this subroutine sets ups a For…Next loop to generate a list of network interfaces installed on the computer, which is then displayed in the ListBox control. Based on the assumption that all computers where this application will run must have at least one active network interface, a default network interface is defined (for example, InterfaceID = System.GetNetworkInterface(0)). The GetNetworkInfo() subroutine is then executed to display network interface data.

The subroutine ends by setting up an Exception handler designed to trap

OutOfBoundsException errors. An OutOfBoundsException error can occur if a network interface displayed by the application is selected after becoming disabled. The event handler prevents this error from crashing the application and, instead, clears out the display area and displays a user-friendly error message.

Adding a Little Program Code

Once you finish configuring the application’s user interface and its menu system, and you add its custom property and methods, it’s time to start adding the program code associated with the application’s controls. Begin by adding the following code statement to the new Open event handler for the lbxInterfaceIDs ListBox control.

RefreshDisplay

This code executes when the application starts or, more specifically, when the window (Window1) containing the ListBox control is loaded. It executes the RefreshDisplay method, which displays a list of all active network interfaces on the computer. Next, add the following code statements to the new Change event handler for the lbxInterfaceIDs ListBox control.

'Set the Network Interface ID equal to the interface selected by the user InterfaceID = System.GetNetworkInterface(me.ListIndex)

GetNetworkInfo() 'Call subroutine that displays network interface data

Exception err 'Trap exceptions

342

C H A P T E R 1 2 D E B U G G I N G R E A L B A S I C A P P L I C A T I O N S

'Exception handler for OutofBoundsException errors If err IsA OutOfBoundsException Then

'Clear out data displayed in EditField controls displayed on the window MacAddressField.Text = ""

IPAddressField.Text = ""

SubnetMaskField.Text = ""

'Display a user friendly error message

MsgBox "This connection is no longer active. Please contact the " _ + "helpdesk for additional assistance."

End If

This code is responsible for calling the GetNetworkInfo() subroutine whenever the user selects a different network interface. Now, add the following code statements to the new Action event handler for the pbnRefresh PushButton control.

'Call subroutine that updates the display of network interface data RefreshDisplay()

This code calls the RefreshDisplay() subroutine whenever the user clicks the PushButton control labeled Refresh.

Testing the Network Connection Checker

That’s it. Go ahead and save the application, naming it Network Connection Checker. Then, put it through its paces to make sure it doesn’t have any errors. Of course, to do so, you need to run it on a computer with at least one, but preferably two or more, network interfaces. If necessary, use the debugging instructions and tips presented in this chapter to track down and fix any errors you may come across. Also, when you do your testing, try disabling one or more network interfaces and see how the application handles it. For example, if you start the application, disable a network interface, and then select it within the application, the application should display the message you see in Figure 12-13. The application should continue running, instead of crashing with a run-time error.

Figure 12-13. As seen on Windows, the Network Connection Checker application displays an informational message when the user selects a network interface that has become inactive.

C H A P T E R 1 2 D E B U G G I N G R E A L B A S I C A P P L I C A T I O N S

343

Here’s another test you might want to try: disable all the computer’s network interfaces before starting the Network Connection Checker application. In this situation, the application should respond by displaying the message you see in Figure 12-14 when it starts up.

Figure 12-14. An informational message tells the user no active network interfaces were found, as seen on Windows.

Assuming the user can enable any failed or disabled network interface devices, the application will correctly report on them when the Refresh button is clicked.

Summary

In this chapter, you learned how to debug your REALbasic applications. This included learning how to track down and fix one or more syntax errors at a time, as well as how to track program flow to ensure things are happening in the order you expect. You also learned how to track the status of variables, properties, and objects, in addition to learning how to set and remove breakpoints. On top of all this, this chapter taught you how to trap exceptions to be able to recover from run-time errors or to present users with friendly and meaningful error messages.

Index

Symbols

#If … #EndIf block, 164, 171–172 & (ampersand) character, 123

+(plus) button, 287

+(plus) character, 158 < operator, 173

<= operator, 173 <> operator, 173

= (equals) operator, 173 > operator, 173

>= operator, 173

A

About window, Help menu, 235 accelerator keys, menus, 105, 118, 121, 123 AcctStatus column, 289

Action event handler, 268, 271, 298, 309, 320, 341

Action events, 29–30, 32, 50, 63, 101, 184 ActionButton, 217 ActionButtonCaptain property, 248 ActiveX controls (Microsoft), 95–96 Add Bookmark menu, Main toolbar, 38 Add Constant button, 235, 263

Add Menu Event Handler button, 157

Add Menu Handler button, 132, 185, 204, 220, 237, 320

Add Method button, 235, 340

Add Module button, 221

Add Property button, 137, 263, 319 Add Window button, 68, 225, 234 Add Window icon, 47

adding new controls, 95

AddRow method, ListBox control, 188, 190

Advanced button, 288, 296 aligning controls, 96–97 alignment tools, 96–97

Alt key, 123

AlternateActionButton, 217

Alternate-MenuModifier property, 121 ampersand (&) character, 123 Analysis, EditField control, 183

And operator, 175

App class object, 263

App item, 22, 75, 177, 293 Append method, 149, 196 AppendToTextFile method, 252 Apple menu, 37, 128

Apple QuickTime, 86, 203 Apple WebKit, 58 AppleMenuItem value, 128 Apples XCode vs. REALbasic, 16 application data overview, 135

application development cycle, 19 Application menu, Mac OS X, 128 application windows, 78 ArrayName, 147

arrays, 146

changing size, 148–149 defined, 138 dimensions, 147 loading data, 147 multidimensional, 147 retrieving data, 148

audio

NotePlayer control, 301, 305–309 Sound class, 301–304

357