E Field VB.NET

Class
System.Math

Syntax
Math.E

Description
This field returns the approximate value of the irrational number e, which is the base of the natural
logarithm and the base of the natural exponential function. In particular:

Math.E = 2.71828182845905

Rules at a Glance
This is a Shared member, so it can be used without creating any objects.

VB .NET/VB 6 Differences
The E Field is new to VB .NET.

End Statement
Syntax
End
End Class
End Enum
End Function
End Get
End If
End Interface
End Module
End Namespace
End Property
End Select
End Set
End Structure
End Sub
End SyncLock
End Try
End With
End While

Description
Ends a procedure or a block of code

Rules at a Glance
The End statement is used as follows:

TABLE

TABLE

Programming Tips and Gotchas
When used alone, the End statement wraps calls to the private FileSystem.CloseAllFiles function, as well as to the System.Environment object's Exit method, making it relatively safe to call to terminate an application. However, it does not release resources not automatically handled by the garbage collector, and does not automatically call the Finalize destructor.

VB .NET/VB 6 Differences

  • In VB 6, the End statement used by itself was to be avoided, since it terminated program execution abruptly without performing normal cleanup operations. In VB .NET, End is much safer, and is not to be avoided.
  • A number of the End... statements are new to VB .NET. These include End Class (classes are defined in saparate CLS files in VB 6), End Get (Property Get statements are terminated with an End Property statement in VB 6), End Interface (interfaces are implemented as virtual base classes in VB 6), End Module (code modules are defined in separate BAS files in VB 6), End Namespace (namespaces do not exist in VB 6), End Set (Property Set and Property Let statements are terminated with an End Property statement in VB 6), End Try (VB 6 does not support structured exception handling), and End While (VB 6 supports the Wend statement to terminate a While loop).

Enum Statement

Syntax

accessmodifier Enum name [As type] membername [= constantexpression] membername [= constantexpression] .. End Enum accessmodifier

accessmodifier

User Optiona Type: Keyword

The possible values of accessmodifier are Public, Private, Friend, Protected, or Protected Friend.
Name

Use: Required Type: String literal

The name of the enumerated data type.

Membername

Use: Required Type: String literal

The name of a member of the enumerated data type.

Constantexpression

Use: Optional Data Type: Long

The value to be assigned to membername.

Type

Use: Optional Type: Keyword

The data type of the enumeration. All enumerated members must be integers; possible values are Byte, Short, Integer, and Long.

Description
Defines an enumerated data type. All of the values of the data type are defined by the instances of membername.

Rules at a Glance

  • The Enum statement can only appear at module level, in the declarations section of a form, code module, or class module.
  • Access rules for Enums are the same as for variables and constants. In particular, the optional accessmodifier can be any one of the following: Public, Private, Protected, Friend, or Protected Friend. The following table describes the effects of the various access modifiers:

TABLE

Rules at a Glance

  • constantexpression can be either a negative or a positive number. It can also be another member of an enumerated data type or an expression that includes integers and enumerated data types.
  • If you assign a floating point value to constantexpression, it is automatically rounded and converted to an integer only if Option Strict is off; otherwise, it generates a compiler error.
  • If you do not specify type, it defaults to Integer.
  • If constantexpression is omitted, the value assigned to membername is 0 if it is the first expression in the enumeration. Otherwise, its value is 1 greater than the value of the preceding membername.
  • The values assigned to membername cannot be modified at runtime

Programming Tips and Gotchas

Once you define an enumerated type, you can use name as the return value of a function. For example, given the enumeration:

  • Public Enum enQuarter
  • enQ1 = 1
  • enQ2 = 2
  • enQ3 = 3
  • enQ4 = 4
  • End Enum

you can use it as the return value of a function, as illustrated by the following function declaration:

Public Function QuarterFromDate(datVar as Date) _As enQuarter

You can also use it in a procedure's parameter list when defining a parameter's data type, as in the following code fragment:

Public Function GetQuarterlySales(intQ As enQuarter) _As Double

  • Although you can declare an enumerated type as the argument to a procedure or the return value of a function, VB .NET does not provide type safety in these cases. That is, if the value of the argument or the return value of the function is outside of the range of the enumerated type, VB .NET does not generate an error. In cases such as these, you should rely on validation routines to make sure that an input value is in fact within the range of an enumerated type.
  • Individual values of an enumerated type can be used in your program just like normal constants, except that they must be prefaced with the name of the enumeration.
  • Enumerated types provide the advantage of allowing you to replace numeric values with more mnemonic labels and of allowing you to select values using the Auto List Members feature in the Visual Studio IDE.

VB .NET/VB 6 Differences

  • In VB 6, members of an enumeration can be accessed without having to qualify them with the name of the enumeration to which they belong. In VB .NET, this behavior is not permitted; all members of an enumeration can only be accessed by referring to the name of their enumeration.
  • In VB 6, all enumerated members are Longs. In contrast, VB .NET allows you to define the integer data type of the enumeration's members.
  • In VB 6, members of a public enumeration can be hidden from the Object Browser by adding a leading underscore to the member name. For example, in the enumeration:
  • Public Enum Primes
  • [_x0] = 0
  • x1 = 1
  • x2 = 3

End Enum

the constant _x0 is hidden in Intellisense and the Object Browser unless the Object Browser's Show Hidden Members option is selected. In Visual Studio .NET, a leading underscore does not hide a member.

Environ Function

Class
Microsoft.VisualBasic.Interaction

Syntax
Environ(expression)
expression

Use: Required Data Type: String, or a numeric expression

If expression is a string, it must be the name of the required environment variable; if expression is numeric, it must be the 1-based ordinal number of the environment variable within the environment table.

Return Value
A String containing the text assigned to expression

Description
Returns the value assigned to an operating-system environment variable

Rules at a Glance

  • A zero-length string ("") is returned if expression does not exist in the operating system's environment-string table or if there is no environment string in the position specified by expression.
  • expression can be either a string or a numeric expression; that is, you can specify one or the other, but not both.

Example

Programming Tips and Gotchas

  • If expression is numeric, both the name and the value of the variable are returned. An equal sign (=) is used to separate them. For example, the function call Environ(1) might return the string TEMP=C:WINDOWSTEMP.
  • If you retrieve environment variables and their values by ordinal position, the first variable is in position 1, not position 0.
  • Due to the flexibility offered, it is now accepted and recommended practice to use the registry for variables needed by your application, rather than the environment-string table.
  • Environment variables can be defined in a variety of ways, including by the AUTOEXEC.BAT and MSDOS.SYS files, as well as by the

HKEY_LOCAL_MACHINESystemCurrentControlSetControlSessionManagerEn vironment and HKEY_CURRENT_USEREnvironment keys in the registry.

VB .NET/VB 6 Differences

  • In VB 6, the Environ function retrieved environmental variables and their values only from the environment-string table. In VB .NET, the function retrieves values both from the environmentstring table and the system registry.
  • In VB 6, the function could be called using either the envstring named argument (if the argument was the name of an environment variable) or the number named argument (if the number represented the ordinal position of the variable in the environment table). VB .NET replaces these with a single named argument, expression.

EOF Function
Class
Microsoft.VisualBasic.FileSystem

Syntax
EOF(filenumber)

filenumber

Use: Required Data: Integer

Any valid file number

Return Value
A Boolean indicating when the end of the file has been reached

Description
Returns a Boolean indicating when the end of the file has been reached. Applies to files opened for binary, random, or sequential input.

Rules at a Glance

  • filenumber must be an Integer that specifies a valid file number.
  • If a file is opened for binary access, you cannot use EOF with the Input procedure. Instead, use LOF and Loc. If you want to use EOF, you must use FileGet rather than Input. In this case, EOF returns False until the previous FileGet procedure is unable to read an entire record.

Example

Programming Tips and Gotchas

  • EOF allows you to test whether the end of a file has been reached without generating an error.
  • Because you always write data to sequential files at the end of the file, the file marker is always at the end of the file, and EOF will therefore always return True when testing files opened with their modes set equal to either Input or Append.

Erase Statement

Syntax
Erase arraylist

arraylist

Use: RequiredDim fr As Integer = FreeFile( ) Data Type: String literal

A list of array variables to clear

Description
Releases an array object. This is equivalent to setting the array variable to Nothing.

Rules at a Glance

  • Specify more than one array to be erased by using commas to delimit arraylist.
  • The Erase statement causes all memory allocated to arrays to be released.

Programming Tips and Gotchas
Once you use Erase to clear an array, it must be redimensioned with ReDim before being used again. This is because Erase releases the memory storage used by the array.

Erl Property

Class
Microsoft.VisualBasic.Information

Syntax
Erl

Return Value
An Integer containing the line number

Description
Indicates the line number on which an error occurred

Rules at a Glance

  • Erl returns the line number only if one has been provided in the source code.
  • If the error occurs on a line that does not have a line number, Erl returns 0.

Programming Tips and Gotchas

  • Erl is not affected by compiler settings. Compiling with the /debug- switch does not prevent Erl from accurately reporting the line number.
  • Line numbers are rarely used in modern VB code. In VB.NET, line numbers are labels that must be followed by a colon.
  • Although programmers have been requesting an error-handling function that reports the line number on which an error occurred, Erl has one major limitation: namely, it requires that the developer assign a line number to source code lines in advance.
  • Erl is not new to VB .NET. It was an undocumented and little known function in previous versions of Visual Basic (and of QBasic as well).

VB .NET/VB 6 Differences
In VB 6, line numbers are distinct from labels, and do not require that any symbol (other than white
space) separate them from that their lines' source code. In VB .NET, line numbers are labels that must
be followed by a colon.

Err Object
Class
Microsoft.VisualBasic.ErrObject

Createable

No

Description
The Err object contains properties and methods that allow you to obtain information about a single runtime error in a Visual Basic program. The Err object also lets you generate errors and reset the error object. Because the Err object is an intrinsic object with global scope (which means that it is part of every VB project you create), you do not need to create an instance of it within your code.

When an error is generated in your application—whether it is handled or not—the properties of the Err
object are assigned values that you can then access to gain information about the error that occurred. You can even generate your own errors explicitly using the Err.Raise method. You can also define your own errors to unify the error-handling process.

When your program reaches an Exit Function, Exit Sub, Exit Property, Resume, or On Error statement, the Err object is cleared and its properties reinitialized. This can also be done explicitly using the Err.Clear method.

Public Instance Properties

TABLE

Public Instance Properties

Public Instance Methods

TABLE

Public Instance Methods

Programming Tips and Gotchas

  • The Visual Basic Err object is not a collection; it only contains information about the last error, if one occurred. You could, however, implement your own error collection class to store a number of errors by copying error information from the Err object into an application-defined error collection object.
  • An Err object cannot be passed back from a class module to a standard code module.
  • VB also supports structured error-handling through the Try...Catch...Finally statement.

Err.Clear Method

Class

Microsoft.VisualBasic.ErrObject

Syntax
Err.Clear( )

Description
Explicitly resets all the properties of the Err object after an error has been handled

Rules at a Glance
You only need to clear the Err object if you need to reference its properties for another error within the
same subroutine, or before another On Error statement within the same subroutine.

Example

Programming Tips and Gotchas

  • Resetting the Err object explicitly using the Clear method is necessary in situations where you are using On Error Resume Next and are testing the value of Err.Number repeatedly. Unless you reset the Err object, you run the very real risk of catching the previously handled error, the details of which are still lurking in the Err object's properties.
  • The Err object is automatically reset when either a Resume, Exit Sub, Exit Function, Exit Property, or On Error statement is executed.
  • You can achieve the same results by setting the Err.Number property to 0; however, your code will be more readable if you use the Clear method. VB also supports structured error-handling through the Try...Catch...Finally statement.
  • Internally, in VB .NET the Err object is an instance of the Microsoft.VisualBasic.ErrObject class. It is returned by the Err property of the Microsoft.VisualBasic.Information class.

Err.Description Property

Class

Microsoft.VisualBasic.ErrObject

Syntax

To set the property: Err.Description = string To return the property value:string = Err.Description

string

Use: Required Data Type: String

Any string expression

Description
A read/write property containing a short string describing a runtime error

Rules at a Glance

  • When a runtime error occurs, the Description property is automatically assigned the standard description of the error.
  • For application-defined errors, you must assign a string expression to the Description property, or the error will not have an accompanying textual message.
  • You can override the standard description by assigning your own description to the Err object for both VB errors and application-defined errors.

Programming Tips and Gotchas

  • If an error occurs within a class module, an ActiveX DLL, or an EXE—regardless of whether it is running in or out of your application's process space—no error information from the component will be available to your application unless you explicitly pass back an error code as part of the error-handling routine within the component. This is done using the Err.Raise method, which allows you to raise an error on the client, passing custom arguments for Number, Source, and Description.
  • If you raise an error with the Err.Raise method and do not set the Description property, the Description property will be automatically set to "Application-efined or Object-Defined Error."
  • You can also pass the Err.Description to a logging device, such as a log file in Windows 95 or the application log in Windows NT, by using the App.LogEvent method, as the following code fragment demonstrates:
  • The best way to set the Description property for your own application-defined errors is to use

the named-description argument with the Raise method, as the following code shows:

  • VB also supports structured error-handling through the Try...Catch...Finally statement.

Err.GetException Method

Class

Microsoft.VisualBasic.ErrObject

Syntax
Err.GetException( )

Return Value
A System.Exception object or an object inherited from it containing the current exception

Description
Returns the Exception object associated with the current exception

Rules at a Glance

  • The GetException method can be called at any time in a program.
  • If there is no exception, the method returns an uninitialized exception object (i.e., an object whose value is Nothing).

Example
The following code renames a file:

If the user inputs an invalid filename in the first input box, the result is the following message that displays information about the error:

Programming Tips and Gotchas

  • The Err.GetException method can be used with the unstructured On Error Resume Next statement as well as with the Try...Catch...End Try structure.
  • Since GetException is a member of the Err object, its major application is to provide access to error information stored to an instance of the Exception class from code that relies on unstructured exception handling.

VB.NET/VB6 Differences

The GetException method is new to VB.NET.

Err.HelpContext Property

Class

Microsoft.VisualBasic.ErrObject

Syntax
Err.HelpContext

Description
A read/write property that either sets or returns an Integer value containing the context ID of the
appropriate topic within a Help file.

Rules at a Glance

  • The Err object sets the HelpContext property automatically when an error is raised if Err.Number is a standard VB .NET error.
  • If the error is user-defined and you don't explicitly set the HelpContext property yourself, the Err object will set the value to 1000095, which corresponds to the "Application-defined or object-defined error" help topic in the VB Help file. (The HelpContext property is set by the fifth parameter to the Err.Raise method.
  • HelpContext IDs are decided upon when writing and creating a Windows Help file. Once the Help file has been compiled, the IDs cannot be changed. Each ID points to a separate Help topic.

Example

Programming Tips and Gotchas

  • You can display a topic from the Visual Basic Help file by using the MsgBox function with the vbMsgBoxHelpButton constant and passing Err.HelpContext as the HelpContext argument (as shown in the previous example). While this is a simple and very effective way to add much more functionality to your applications, bear in mind that some of your users could find the explanations within the VB Help file somewhat confusing. If time and budget allow, the best method is to create your own help file (for which you will need the Help compiler and other Help file resources from the full version of VB) and to pass both the HelpContext and HelpFileName to MsgBox.
  • Some objects that you may use within your application have their own help files, which you can access using HelpContext to display highly focused help to your users.
  • Err.HelpFile Property

    Class

    Microsoft.VisualBasic.ErrObject

    Syntax
    Err.HelpFile

    Description
    A read/write String property that contains the fully qualified path of a Windows Help file.

    Rules at a Glance
    The HelpFile property is automatically set by the Err object when an error is raised.

    Example

    See Err.HelpContext Property.

    Programming Tips and Gotchas

  • You can display a topic from the Visual Basic Help file by using the MsgBox function with the vbMsgBoxHelpButton constant and passing Err.HelpFile as the HelpFile argument (as shown in the example for the Err.HelpContext property). While this is a simple and very effective way to add more functionality to your applications, bear in mind that some of your users could find the explanations within the VB Help file somewhat confusing. If time and budget allow, the best method is to create your own help file (for which you will need the Help compiler and other Help file resources from the full version of VB) and to pass both the HelpContext and HelpFileName to MsgBox.
  • Some objects that you may use within your application have their own help files, which you can access using HelpFile to display highly focused help to your users.
  • Remember that once the program encounters an Exit... statement or an On Error statement, all the properties of the Err object are reset; this includes the Help file. You must therefore set the Err.HelpFile property each time that your application needs to access the help file.
  • Err.LastDLLError Property

    Class

    Microsoft.VisualBasic.ErrObject

    Syntax

    Err.LastDLLError

    Description
    A read-only property containing a system error code representing a system error produced within a
    DLL called from a VB program.

    Rules at a Glance

  • Only direct calls to a Windows system DLL from VB code will assign a value to LastDLLError.
  • The value of the LastDLLError property depends upon the particular DLL being called. Your code must be able to handle the various codes that can be returned by the DLL you are calling.
  • Don't forget that a failed DLL call does not itself raise an error within your VB program. As a result, the Err object's Number, Description, and Source properties are not filled.
  • Programming Tips and Gotchas

  • The LastDLLError property can be changed by VB at any time, so it is important to save the value in an independent variable as soon as possible.
  • The LastDLLError property is only used by system DLLs, such as kernel32.dll. Therefore, errors that occur within DLLs you may have created will not cause an error code to be assigned to the property.
  • Obtaining accurate documentation about the return values of system DLLs can be a challenging experience! Most useful information can be found by studying the API documentation for Visual C++. However, you can use the Win32 API FormatMessage function to return the actual Windows error message string from within Kernel32.DLL, which incidentally will also be in the correct language. The following is a brief example that you can use in your applications to display the actual Windows error description:
  • Here's a snippet demonstrating how you can use this utility function:

  • Note that some API calls return 0 to denote a successful function call, and others return 0 to
  • denote an unsuccessful call. You should also note that some API functions do not appear to set the LastDLLError property. In most cases, these are functions that return an error code. You could therefore modify the previous snippet to handle these cases:

    Err.Number Property

    Class

    Microsoft.VisualBasic.ErrObject

    Syntax

    Err.Number

    Description
    A read/write property containing a numeric value that represents the error code for the last error
    generated.

    Rules at a Glance

  • When a runtime error is generated within the program, the error code is automatically assigned to Err.Number.
  • The Number property is updated with an application-defined error whose code is passed as an
  • argument to the Err.Raise method.

  • When using the Err.Raise method in normal code, your user-defined error codes cannot be greater than 65536 nor less that 0. (For an explanation, see the final note in Programming Tips and Gotchas of Err.Raise Method.)
  • VB reserves error numbers in the range of 1-1000 for its own trappable errors. In addition, error numbers from 31001 to 31037 are also used for VB trappable errors. In implementing a series of application-defined errors, your error handlers should either translate application errors into VB trappable errors or, preferably, assign a unique range to application-defined errors.
  • When using the Err.Raise method in ActiveX objects, add the vbObjectError constant (-2147221504) to your user-defined error code to distinguish OLE errors from local-application errors.
  • When control returns to the local application after an error has been raised by the OLE server, the application can determine that the error originated in the OLE server and extract the error number with a line of code like the following:
  • Programming Tips and Gotchas

  • An error code is a useful method of alerting your program that a function within an ActiveX or class object has failed. By returning a number based on the vbObjectError constant, you can easily determine that an error has occurred. (vbObjectError is a constant that is defined in the microsoft.VisualBasic.Constants class.) By then subtracting vbObjectError from the value returned by the object's function, you can determine the actual error code:
  • You can create a sophisticated multiresult error-handling routine by using the Err.Number property as the Case statement within a Select Case block, taking a different course of action for different errors, as this snippet demonstrates:
  • Directly assigning a Visual Basic-defined error code to the Number property does not automatically update the Description or other properties of the Err object.
  • Err.Raise Method

    Class

    Microsoft.VisualBasic.ErrObject

    Syntax
    Err.Raise(number, source, description, _
    helpfile, helpcontext)

    number

    Use: Required

    Data Type: Long integer A numeric identifier of the particular error

    source

    Use: Optional Data Type: String

    e object or application responsible for generating the error

    description

    Use: Optional Data Type: String

    A useful description of the error

    helpfile

    Use: Optional Data Type: String

    The fully qualified path of a Microsoft Windows Help file containing help or reference material about the error

    helpcontext

    Use: Optional Data Type: Long

    The context ID within helpfile

    Description
    Generates a runtime error

    Rules at a Glance

  • To use the Err.Raise method, you must specify an error number.
  • If you supply any of the number, source, description, helpfile, and helpcontext arguments when you call the Err.Raise method, they are supplied as values to the Number, Source, Description, HelpFile, and HelpContext properties, respectively. Refer to the entries for the individual properties for full descriptions of and rules for each property.
  • The number argument is a Long integer that identifies the nature of the error. Visual Basic errors (both Visual Basic-defined and user-defined errors) are in the range 0-65535. The range 0-512 is reserved for system errors; the range 513-65535 is available for user-defined errors. When setting the Number property to your own error code in a class module, you add your error-code number to the vbObjectError constant.
  • Programming Tips and Gotchas

  • The Err.Raise method replaces the older Error statement, which should not be used in new code.
  • The Raise method does not reinitialize the Err object prior to assigning the values you pass in as arguments. This can mean that if you Raise an error against an Err object that has not been cleared since the last error, any properties for which you don't specify values will still contain the values from the last error.
  • As well as using Raise in a runtime scenario, you can put it to good use in the development stages of your program to test the viability of your error-handling routines under various circumstances.
  • The fact that Err.Number only accepts numbers in the range 0-65536 may appear to be strange at first because the data type of the Error Number parameter in the Raise event is a Long. However, deep in the recesses of the Err object, the error code must be declared as an unsigned integer—a data type not supported by VB.
  • Err.Source Property

    Class

    Microsoft.VisualBasic.ErrObject

    Syntax

    Err.Source

    Description
    A read/write string property containing the name of the application or the object that has generated the error.

    Rules at a Glance

  • When a runtime error occurs in your code, the Source property is automatically assigned the project name (that is, the string that is assigned to the project's Name property). Note that this is not necessarily the filename of the project file.
  • For clarity of your error messages, when you raise an error in a class module, the format of the source parameter should be project.class.
  • Programming Tips and Gotchas
    Knowing what type of error has occurred within a program without knowing where the error was
    generated is often of little use to the programmer. However, if you enhance the standard Source by
    adding the name of the procedure, you can cut your debugging time dramatically.

    Error Statement

    Syntax
    Error [errornumber]

    errornumber

    Use: Optional Data Type: Long

    Any valid error code

    Description
    Raises an error

    Rules at a glance
    The Error statement is included only for backward compatibility; instead, if you're using standard Visual Basic error handling, you should use the Err.Raise method and the Err object. Otherwise, you should use structured exception handling with the Try...Catch construct.

    Programming Tips and Gotchas
    The Error statement has been a "compatibility" statement for several versions of Visual Basic. Interestingly, it managed to survive the general purge of outdated language elements. Despite its persistence, we still recommend that its use be strictly avoided.

    ErrorToString Function

    Class

    Microsoft.VisualBasic.Conversion

    Syntax
    ErrorToString([errornumber])
    errornumber

    Use: Optional Data Type: Long

    A numeric error code

    Return Value
    A String containing an error message

    Description
    Returns the error message or error description corresponding to a particular error code

    Rules at a Glance

  • If errornumber is present, the function returns the text of the error message corresponding to that error code.
  • If no arguments are passed to the function, it returns the text of the error message corresponding to the Description property of the Err Object.
  • Event Statement

    Syntax
    [Public] Event eventName [(arglist)]

    Public Use: Optional
    Type: Keyword

    Indicates that the event is visible throughout the project

    eventName

    Use: Required Type: String literal

    The name of the event arglist is optional and has the following syntax:
    [ByVal | ByRef] varname[( )] [As type]

    ByVal

    User Optional Type: Keyword

    The argument is passed by value; that is, a local copy of the variable is assigned the value of the argument.

    ByRef Use: Optional Type: Keyword

    The argument is passed by reference; that is, the local variable is simply a reference to the argument being passed. All changes made to the local variable are reflected in the calling argument. ByRef is the default method of passing variables.

    varname

    Use: Required Type: String literal

    The name of the local variable containing either the reference or value of the argument.

    type

    Use: Optional Type: Keyword

    The data type of the argument. It can be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, Date, String, Object, or any user-defined type, object type, or data type BCL.

    Description
    Defines a custom event that the object can raise at any time using the RaiseEvent statement.

    Rules at a Glance

  • The event declaration must be Public so that it is visible outside the object module; it cannot be declared as Friend or Private. However, the Public keyword can be omitted from the declaration, since it is Public by default.
  • An Event statement can only appear in the Declarations section of an object module, that is, in a form or class module.
  • Example
    The following code snippet demonstrates how you can use an event to communicate a status message back to the client application. To take advantage of this functionality, the client must declare a reference to this class using the WithEvents keyword.

    Programming Tips and Gotchas

  • To allow the client application to handle the event being fired, the object variable must be declared using the WithEvents keyword.
  • VB custom events do not return a value; however, you can use a ByRef argument in arglist to simulate a return value. For more details, see the RaiseEvent statement.
  • Unlike parameter lists used with other procedures, Event parameters lists cannot include Optional or ParamArray arguments or default values.
  • If you use the Event statement in a standard interface class (i.e., a class in which only properties and methods are defined, but no code is included in the procedures) for use with the Implements statement, the Implements statement does not recognize the "outgoing interfaces" used by events, and therefore the event will be ignored.
  • Exception Class

    Namespace

    System

    Createable

    Yes

    Description
    The Exception class and its inherited (child) classes represent runtime exceptions.

    Selected Exception Class Members
    The following provides a brief description of the more important members of the Exception class:

    HelpFile property
    Sets or retrieves a link to the help file associated with the exception. Its value is a Uniform Resource Name (URN) or Uniform Resource Locator (URL).

    InnerException property
    Returns a reference to the inner Exception object in the case of nested exceptions.

    Message property
    Returns the text of the error message.

    Source property
    Returns or sets a string containing the name of the application or the object that causes the error.

    StackTrace property
    Returns a string (the stack trace) consisting of a list of all methods that are currently in the stack. The following shows a stack trace when the procedure DoArithmetic calls the procedure Arithmetic, which generates an exception that is thrown up to DoArithmetic (the string has been formatted to fit the margins of the page):

    at WindowsApplication6.Form1.Arithmetic(String Action, Double x,
    Double y) in C:ProjectsWindowsApplication6Form1.vb:line 68

    at WindowsApplication6.Form1.DoArithmetic( ) in
    C:ProjectsWindowsApplication6Form1.vb:line 87

    TargetSite property
    Returns a MethodBase object representing the method that throws the exception. For example, if e is the exception whose stack trace is shown in the discussion of the StackTrace property, then the code.
    e.TargetSite.Name
    will return the string Arithmetic.
    GetBaseException Method
    This method returns the exception object for the innermost exception. For instance, in the previous example (see the discussion of the StackTrace property) the code:

    e.GetBaseException.ToString

    returns the string:

    ToString Method
    Returns the fully qualified name of the exception and possibly the error message, the name of the inner exception, and the stack trace.

    Children of the Exception Class
    The System namespace contains the Exception class, which is the base class for a substantial collection of derived exception classes, listed as follows. Note that the indentation indicates class inheritance. For example, EntryPointNotFoundException (the fifth from the last entry in the list) inherits from typeLoadException.

    Programming Tips and Gotchas

  • As Microsoft states: "Most of the exception classes that inherit from Exception do not implement additional members or provide additional functionality." Thus, it is simply the class name that distinguishes one type of exception from another. The properties and methods applied to an exception object are inherited from the Exception base class.
  • You can trap the generic Exception object, or you can trap a specific exception object. There are two circumstances in particular when you may want to trap a specific exception, rather than the more general Exception object:
  • o You want to handle errors differently based on their class. For instance, you may want to issue different custom error messages for different exception types.
    o You want to take advantage of members of a particular exception class that are not implemented in the Exception base class. For instance, the ArgumentException class has a ParamName property that returns the name of the parameter that causes the exception. If you trap the Exception class rather than the ArgumentException class, this member is unavailable.

    VB .NET/VB 6 Differences
    The Exception class, along with Structured Exception Handling (SEH), is new to the .NET platform.

    Exit Statement
    Syntax
    Exit Do
    Exit For
    Exit Function
    Exit Property
    Exit Select
    Exit Sub
    Exit Try
    Exit While

    Description
    Prematurely exits a block of code

    Rules at a Glance
    Exit Do
    Exits a Do...Loop statement. If the current Do...Loop is within a nested Do...Loop, execution continues with the next Loop statement wrapped around the current one. If, however, the Do...Loop is standalone, program execution continues with the first line of code after the Loop statement.

    Exit For
    Exits a For...Next loop or a For Each...Next statement. If the current For...Next is within a nested For...Next loop, execution continues with the next Next statement wrapped around the current one. If, however, the For...Next loop is standalone, program execution continues with the first line of code after the Next statement.

    Exit Function
    Exits the current function. Program execution is passed to the line following the call to the function.

    Exit Property
    Exits the current property procedure. Program execution is passed to the line following the call to the property.

    Exit Select
    Immediately exits a Select Case construct. Execution continues with the statement immediately following the End Select statement.

    Exit Sub
    Exits the current sub procedure. Program execution is passed to the line following the call to the procedure.

    Exit Try
    Immediately exits a Try...Catch block. Program execution proceeds with the Finally block, if it is present, or with the statement following the End Try statement.

    Exit While
    Immediately exists a While loop. Program execution proceeds with the code following the End While statement. If Exit While is within a nested While loop, it terminates the loop at the level of nesting in which Exit While occurs.

    Programming Tips and Gotchas
    Using Exit Sub can save having to wrap lengthy code within an If...Then statement. Here is an example with Exit Sub:


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

VB.NET Topics