33
Empty, Null, Missing, IsNull, IsObject,
and IsMissing Are Gone
Before VB .NET
The traditional VB Variantdata type could hold some special kinds of
values: Null(not known), Empty(no value was ever assigned to this vari-
able), and Missing(this variable was not sent, for example, as part of a
procedure’s parameters).
Nullwas sometimes used to identify fields in databases that are not avail-
able (or unknown), while the Emptycommand was used to represent some-
thing that didn’t exist (as opposed to simply not being currently available).
Some programmers used the IsMissingcommand to see if an optional para-
meter had been passed to a procedure:
Sub SomeSub(Optional SomeParam As Variant)
If IsMissing(SomeParam) Then
VB .NET
The VB .NET Objectdata type does not use Missing, Empty, or Null. There
is an IsDBNullfunction that you can use with databases instead of the now-
missing IsNullcommand. Similarly, an IsReferencecommand replaces the
IsObjectcommand.
Optional parameters can still be used with procedures, but you must declare
that As Typeand you must also supply a default value for them. You cannot
write code within a procedure that will tell you whether a particular parame-
ter has been passed. For further details, see the section titled “Optional
Parameter-Passing Tightened,” in this appendix.
If you need to test whether an optional parameter has been passed, you can
overload a procedure. Overloading is a new technique in which a function
(or indeed a method or property) can be made to behave differently based
on what is passed to it. For more on overloading, see the section titled
“Overloaded Functions, Properties, and Methods (Overloading)” in this
appendix.
Also see “IsEmpty.”
BC43
Appendix B: A Dictionary of VB .NET
29
Environment Information
See “Directory (Current).”
Error Messages (Obscure)
Some .NET error messages can be confusing. They merely offer some general
abstract comment, without telling you precisely the punctuation or syntax
you must use to fix the problem.
For example, you might get an error message like this:
Value of type system.drawing.color cannot be converted to 1-
dimensional array of system.drawing.color.
This code results in that error message:
Dim ArrColor() As Color = Color.Gold
To fix the problem, enclose the color in braces:
Dim ArrColor() As Color = {Color.Gold}
Error Handling Revised
Before VB .NET
Don’t panic. You can still use the familiar VB error-handling techniques
(On Error...).
Thus, you don’t have to revise this aspect of your older programs. But for
new programs that you write in VB .NET, you might want to consider the pos-
sibility that a superior error-trapping and handling approach exists. They call
it structured error handling,which implies that your familiar, classic VB error
handling is . . . well . . . unstructured.
If you try to write something traditional, like If Err Then, however, you’ll
be informed that VB .NET doesn’t permit the ErrObjectto be treated as
Boolean(true/false). However, where there’s a will, there’s a way. You can
test the Errobject’s number property. So, if you want to test the Errobject
within an If...Thenstructure, use this VB .NET code:
BC44
Visual Basic 2005 Express Edition For Dummies
32
x = CInt(textbox1.Text)
If err.Number <> 0 Then
textbox1.Text = “You must enter a number...”
End If
VB .NET
Consider using the new Try...Catch...Finallystructure:
Sub TryError()
Try
Microsoft.VisualBasic.FileOpen(5, “A:\Test.Txt”,
OpenMode.Input)
Catch er As Exception
MessageBox.Show(er.ToString)
Finally
End Try
End Sub
Code between the Tryand End Trycommands is watched for errors. You
can use the generic Exception(which will catch any error) or merely trap a
specific exception, such as the following:
Catch er As DivideByZeroException
The term exceptionis used in C-like languages (and now in VB .NET) to mean
error.
I used er, but you can use any valid variable name for the error. Or you can
leave that variable out entirely and just use Catch, like this:
Try
Microsoft.VisualBasic.FileOpen(5, “A:\Test.Txt”,
OpenMode.Input)
Catch
MessageBox.Show(“problem”)
Finally
End Try
BC45
Appendix B: A Dictionary of VB .NET
42
If an error occurs during execution of the source code in the Trysection, the
following Catchsection is then executed. You must include at least one
Catchsection, but there can be many such sections if you need them to test
and figure out which particular error occurred. A series of Catchsections is
similar to the Casesections in Select...Casestructures. The Catchsec-
tions are tested in order, and only one Catchblock (or none) is executed for
any particular error.
You can use a Whenclause to further specify which kind of error you want to
trap, like this:
Dim Y as Integer
Try
Y = Y / 0
Catch When y = 0
MessageBox.Show(“Y = 0”)
End Try
Or you can specify a particular kind of exception, thereby narrowing the
number of errors that will trigger this Catchsection’s execution:
Catch er As ArithmeticException
MessageBox.Show(ÒMath error.Ó)
Catch When y = 0
MessageBox.Show(“Y = 0”)
End Try
To see a list of the specific exceptions, use the VB .NET menu Debug➪
Windows➪Exceptions and then expand the Common Language Runtime
Exceptions. You may have to do a bit of hunting. For instance the FileNot
Founderror is located two expansions down in the hierarchy: Common
Language Runtime➪SystemException➪IOException. So you have
to expand all three (click the + next to each) in order to finally find
FileNotFoundException.
Also notice in the Exceptions window that you can cause the program to ignore
any of the exceptions (click the Continue radio button in the Exceptions
window). This is the equivalent of On Error Resume Nextin VB 6.
Here is a list of common errors you can trap in VB .NET. The following errors
are in the System namespace:
AppDomainUnloadedException
ApplicationException
ArgumentException
ArgumentNullException
ArgumentOutOfRangeException
ArithmeticException
BC46
Visual Basic 2005 Express Edition For Dummies
51
ArrayTypeMismatchException
BadImageFormatException
CannotUnloadAppDomainException
ContextMarshalException
DivideByZeroException
DllNotFoundException
DuplicateWaitObjectException
EntryPointNotFoundException
Exception
ExecutionEngineException
FieldAccessException
FormatException
IndexOutOfRangeException
InvalidCastException
InvalidOperationException
InvalidProgramException
MemberAccessException
MethodAccessException
MissingFieldException
MissingMemberException
MissingMethodException
MulticastNotSupportedException
NotFiniteNumberException
NotImplementedException
NotSupportedException
NullReferenceException
ObjectDisposedException
OutOfMemoryException
OverflowException
PlatformNotSupportedException
RankException
ServicedComponentException
StackOverflowException
SystemException
TypeInitializationException
TypeLoadException
TypeUnloadedException
UnauthorizedAccessException
UnhandledExceptionEventArgs
UnhandledExceptionEventHandler
UriFormatException
WeakReferenceException
The following errors are in the SystemIOcategory:
DirectoryNotFoundException
EndOfStreamException
FileNotFoundException
InternalBufferOverflowException
IOException
PathTooLongException
BC47
Appendix B: A Dictionary of VB .NET
47
You can list as many Catchphrases as you want and respond individually to
them. You can respond by notifying the user as you did in the previous exam-
ple, or merely by quietly fixing the error in your source code following the
Catch. You can also provide a brief error message with the following:
e.Message
Or, as you did in the previous example, use the following fully qualified error
message:
e.ToString
Here’s the full Try...Catch...Finallystructure’s syntax:
Try trystatements
[Catch
1
[exception [As type]] [When expression]
catchStatements
1
[Exit Try]
Catch
2
[exception [As type]] [When expression]
catchStatements
2
[Exit Try]
...
Catch
n
[exception [As type]] [When expression]
catchStatements
n
]
[Exit Try]
[Finally
finallyStatements]
End Try
Recall that following the Tryblock, you list one or more Catchstatements.
A Catchstatement can include a variable name and an Asclause defining
the type of exception or the general “all errors,” As Exception (er As
Exception). For example, here’s how to trap all exceptions:
Try
Microsoft.VisualBasic.FileOpen(5, “A:\Test.Txt”,
OpenMode.Input)
Catch e As Exception
‘Respond to any kind of error.
Finally
End Try
And here is how to respond to the specific File Not Found error:
BC48
Visual Basic 2005 Express Edition For Dummies
35
Try
Microsoft.VisualBasic.FileOpen(5, “A:\Test.Txt”,
OpenMode.Input)
Catch FileNotFoundE As FileNotFoundException
‘Respond to this particular error here, perhaps a
messagebox to alert the user.
Finally
End Try
An optional Exit Trystatement causes program flow to leap out of the
Trystructure and to continue execution with whatever follows the End Try
statement.
The Finallystatement should contain any code that you want executed after
error processing has been completed. Any code in the Finallysection is
alwaysexecuted, no matter what happens (unlike source code following the
End Tryline, which may or may not execute, depending on how things go
within the Trystructure). Therefore, the most common use for the Finally
section is to free up resources that were acquired within the Tryblock. For
example, if you were to acquire a Mutex lock within your Tryblock, you would
want to release that lock when you were done with it, regardless of whether
the Tryblock exited with a successful completion or an exception (error). It’s
typical to find this kind of code within the Finallyblock:
objMainKey.Close()
objFileRead.Close()
objFilename.Close()
Use this approach when you want to close, for instance, an object reference
to a key in the Registry, or to close file references that were opened during
the Trysection (“block”) of code.
Here’s how source code you put within the Finallysection differs from
source code you put following the End Tryline.
If there is an error, here is the order in which code execution takes place:
1.Trysection
2.Catchsection (the Catchsection that traps this error)
3.Finallysection
BC49
Appendix B: A Dictionary of VB .NET
22
If no error occurs, here is the execution order:
1.Trysection
2.Finallysection
3.Source code following the End Tryline
Even if a Catchsection has an Exit Subcommand, the Finallysection
nevertheless will still be executed. Finallyis always executed. However, the
Exit Subdoes get executed just after the Finallyblock.
Event Handlers
See “Handles” and “Multiple handles,” under the main heading “Control
Arrays Are Gone.”
Executable
See “Deployment.”
File I/O Commands Are Different
Before VB .NET
The familiar syntax is as follows:
Open filepath {For Mode}{options}As {#} filenumber {Len =
recordlength}
For example:
Open “C:\Test.Txt” As 5
Some people refer to the filenumber as the channel.
BC50
Visual Basic 2005 Express Edition For Dummies
Documents you may be interested
Documents you may be interested