Você está na página 1de 30

2

Introduction
Major Error Types
Syntax errors
Run time errors
Logical Errors
Debugging
Debugging using Breakingpoints
Debugging using Watchs
Debugging using Locals
Error handling
Try Catch in VB .NET
Using Structured Error Handling
3
Bug is to mean an error. Debug is the process of removing
errors from a program
Debugging is an essential part of any development project,
as it helps you find errors in your code and in your logic.
Unless you write perfect code every time, there's no getting
away from debugging.
However, no matter how good your code is, there are always
going to be some unexpected circumstances that will cause
your code to fail.
If you do not anticipate and handle errors, your users will see
a default error message about an unhandled exception,
which is provided by the common language run - time
package.
Default error message is not user-friendly it does not clearly inform
users
About what is going on
How to correct it
Visual Studio 2008 has a sophisticated debugger built right
into the development environment. It also provides common
structured error - handling functions that are used across all
languages.
4
Error types can be broken down into three major
categories: syntax (design time), execution, and logic.
Syntax errors
These occur when the environment you're programming in
doesn't understand your code. These are easy to track down in
VB.NET, because you get a blue wiggly line pointing them out. If
you try to run the programme, you'll get a dialogue box popping
up telling you that there were Build errors.
Runtime errors
Are those which occur when the program is running. They are
harder to track down.
Example
Trying to access a file that doesn't exist. Runtime errors usually cause
your programme to crash. If and when that happens, you get the blame.
After all, you're the programmer, and you should write code to trap
runtime errors.
If you're trying to open a database in a specific location, and the
database has been moved, a Runtime error will occur. It's your job to
predict a thing like this, and code accordingly.
5
Logic errors
Are those which cause your code behave in different
way than you thought it would. These errors also occur
when the program is running.
A classic example is creating an infinite loop of the
type "Do While x is greater than 10".
If x is always going to be greater than 10, then the
loop has no way to exit, and just keeps going round
and round.
Logic errors tend not to crash your program. But they
will ensure that it doesn't work properly.
6
VB.net 2008 provides two ways to correct errors in a
given program.
1. Instant syntax checking of variables and objects
2. Error List window
Instant syntax checking of variables and objects and lets you know
immediately when you have a syntax error.
Visual Studio 2008 underlines syntax errors with a blue wavy
line.
If the IDE can automatically correct the syntax error, youll see a
little gray rectangular box at the end of the blue wavy line.
When you hover (move) your mouse over the code in
error, you ll receive a tooltip, telling you what the error
is, and a small gray box with a red circle and a white
exclamation point.
If you move your mouse into the gray box, a down arrow
appears to let you know that a dialog box is available
with some suggested error correction options.
7
Clicking the down arrow or pressing Shift+Alt+F10
causes the Error Correction Options dialog box to
appear as shown in the figures below.
This dialog box presents one or more choices to you for
correcting the error. In this instances, three and one
choice(s) to correct the syntax error as shown in the
dialog boxes below.
Note that the dialog box shows you how your code can
be corrected:
8
Another option available for reviewing all the errors in your code is
the Error List window.
This window displays a grid with all the errors descriptions, the
files they exist in, and the line numbers and column numbers of the
error.
If your solution contains multiple projects, it also displays the
project that each error exists in.
The Error List can be accessed by clicking the Error List tab at the
bottom of the IDE if it is already displayed in the IDE or by clicking
the View Error List menu item.
When the Error List window is displayed, you can double - click
any error to be taken to that specific error in your code.


9
The IDE also provides IntelliSense to assist in preventing
syntax errors.
IntelliSense provides a host of features such as providing a
drop - down list of members for classes, structures, and
namespaces.
IntelliSense initially displays a list of all members for the
object being worked with, and as soon as you start typing
one or more letters the list of members is shortened to match
the letters that you have typed
These IntelliSense features provide two major benefits.
First, you do not have to remember all the available members for the
class. You simply scroll through the list to find the member that you
want to work with or you type the first letter or two of the member to
have the list of members reduced to the relevant members.
Second, the features help you prevent syntax errors because you are
less likely to misspell member names or try to use members that do not
exist in the given class.
Another great feature of IntelliSense is that it
provides a parameter list for the method that you
are working with. IntelliSense lists the number, names,
and types of the parameters required by the function.

10
Developers need to anticipate the possibility of execution
errors and build appropriate error handling logic.
Implementing the appropriate error handling does not
prevent execution errors, but does allow you to handle
them either by gracefully shutting down your application
or bypassing the code that failed and giving the user the
opportunity to perform that action again.
The best way to prevent execution errors is to try
anticipating the error before it occurs and to use error
handling to trap and handle the error. You must also
thoroughly test your code before deploying it.
Dim Num1, Num2 As Integer
Num1 = 10
Num2 = 0
TextBox1.Text = CInt(Num1 / Num2)

11
Run the program and the following error will appear
Dim Num1, Num2 As Integer
Num1 = 10
Num2 = 0
If Num2<> 0 then
TextBox1.Text = CInt(Num1 / Num2)
Else
msgBox(duniminetetor is zero)
End If


12
Logic errors (or semantic errors ) give unexpected or
unwanted results because you did not fully understand
what the code you were writing did.
Private Sub PerformLoopExample()
Dim intIndex As Integer
Do While intIndex < 10
...perform some logic
Loop
End Sub
If the code inside the loop does not set intIndex to
10 or above, this loop just keeps going forever.
Logic errors can be the most difficult to find and
troubleshoot, because it is very difficult to be sure
that your program is completely free from logic
errors.
13
Dim x As Integer
Dim y As Integer
Dim answer As Integer
x = 10.5
y = 3
answer = x * y
TextBox1.Text = answer
What will happen if you run the above code fragment?
You'd think that 10.5 multiplied by 3 would give you the answer 31.5. Click
your button. The answer that appears in your textbox is 30!
This is a logic error: when you don't get the answer you thought you'd get.
The problem, if you were paying attention during the variable types
sections, is that we are trying to put floating point numbers into an Integer
variable type. The Integer variable only works with whole numbers. When
you assign 10.5 to the variable x, the point 5 on the end gets chopped off.
So only the 10 gets stored in x. 10 times 3 is thirty, and this is the answer
that appears in the textbox.
But the point is that VB.NET did not raise a Design-time error. Nor did it
raise a Runtime error. The programme executed, and did not "bug out"
on us. It just didn't give you the answer you expected - it was a logic error.

14
Dim i As Integer
Dim LetterCount As Integer
Dim strText As String
Dim letter As Char
strText = "Debugging"
For i = 1 To strText.Length 1
letter = strText.Substring(1)
If letter = "g" Then
LetterCount = LetterCount + 1
End If
Next
TextBox1.Text = "G appears " & LetterCount & " times"
All the code does is to try and count how many times the letter "g" appears
in the word "Debugging". We're using a For loop, and Substring to get one
letter at a time. This single letter is then placed inside the variable called
letter. An If Statement is used to check if the letter is a "g". If it is, we
increment the LetterCount variable. The answer we're expecting in the
textbox is 3. Except, we don't get 3. We get zero:
There were no wiggly lines and therefore no Build errors. When the button
was clicked, a Runtime exception did not crash the programme. So that
leaves a logic error. But where is it?

15
There were no wiggly lines and therefore no Build errors. When the
button was clicked, a Runtime exception did not crash the
programme. So that leaves a logic error. But where is it?
To help you find out what went wrong, there is three tools in VB .NET
namely Breakpoint, Watch Window and Locals window.
Breakpoint
This allows you to set breakpoints, which temporarily halt the
program when the program executes the line with the breakpoint.
Halting your code with breakpoints and stepping through code allows
you to see where the program may be having problems and also lets
you check the values of the data the program is using while it
executes.
To begin stepping through the code, press F11, and select the Step
Into command from the Debug menu, or the Step Into button on the
Debug toolbar.
You can also press F10 or use the Step Over command. Both allow
you to step through your code one line at a time, pressing F10 or
F11 to proceed with the next line.
The difference between the two is that Step Into steps into a function
call, whereas Step Over executes a function at its call, but does not
step into its code.

16
Most of the time, stepping through the program in its
entirety is very impractical because of the program's
size.
Setting a breakpoint somewhere in the code allows the
program to run normally until the breakpoint is reached.
This allows you to examine the data, check the logic,
and so on, and then either continue execution by
pressing F5 (or Start) again, or step through the code
(F10 or F11).
To insert a breakpoint,
place the cursor on the line of code where you want to break
the execution and press F9.
You can also click on the margin to the left of your
code.
If you want to remove a breakpoint, place the
cursor on the line with the breakpoint you want
to remove and press F9 again, or click on the
breakpoint symbol you want to remove.

17
You can display the Breakpoints window, if the tab is not
shown, in the bottom - right of the IDE by clicking the
Breakpoints icon on the Debug toolbar or by selecting Debug
Windows Breakpoints.
The Breakpoints window shows what line of code the current
breakpoint is at, any conditions it has, and the hit count if
applicable.
You will also notice that each breakpoint listed in the window
has a checkbox beside it. These give the option of activating
or deactivating any breakpoint without actually having to
physically remove the breakpoint from the code view pane.
Some more advanced features are also available. Select any
one of the breakpoints in the Breakpoints window and right
click on it.
Here you can set a condition for the breakpoint.
Click the Condition button and you will see the dialog box.
In this dialog box, we can specify any Boolean condition to determine
whether the breakpoint should be enabled or disabled.
If you click the Hit Count button from the Breakpoint properties
dialog box, you can specify how many times the breakpoint must
be hit before it is automatically enabled.
That is The Breakpoint Hit Count dialog box allows you to define the
number of executions of a loop should be performed before the IDE
stops execution of your code and puts it into break mode.

Watches provide us with a mechanism where we can
interact with the actual data that is stored in our
programs at runtime.
They allow us to see the values of variables and the
values of properties on objects. In addition to being able
to view these values, you can also assign new values.
This can be very handy while stepping through your
code because you can see what would happen if a
variable had a different value at a specific point in time.
In order to use the Watch window, the application must
be in break mode.
Lets develop a simple application which takes two
numbers from a user and calculates the sum,
difference, product and quotients of the numbers.
Add two text boxes and a button on form you get by
launching a new project.
Double click the button and add the following code
1. Dim fn, sn, sum, prod As Integer
2. Dim output As String
3. fn = Val(txtfn.Text)
4. sn = Val(txtsn.Text)
5. sum = fn + sn
6. prod = fn * sn
7. output = "Sum = " + sum.ToString + vbCrLf + "Product = "
+ prod.ToString
8. MsgBox(output)
Add breakpoint at line 7 and run the application and
click on the button
To display the quickWatch
window, make you application
in break mode, then click debug
menu---QuickWatch
Place(click) the cursor on one
of the variables (for example
sum) and choose debug
Quickwatch
A QuickWatch window will
appear showing the variables
name, value and type.
You can watch the values and
types of variables by typing the
variable name at the
expression text box and click
Reevalute button.
To see more than one variables values and type at the same
time you can use watch window. Click Add Watch from
QuickWatch window or choose Debug window watch
while your application is running
The Locals window is similar to the Watch window,
except that it shows all variables and objects for the
current function or procedure.
The Locals window also lets you change the value of a
variable or object. The text for a value that has just
changed also turns red, making it easy to spot the
variable or object that has just changed.
The Locals window is great if you want a quick glance
at everything that is going on in a function or
procedure, but it is not very useful for watching the
values of one or two variables or expressions.
The reason for this is that the Locals window contains
all variables and objects in a procedure or function-
you have to scroll through the window constantly to
view the various variables and objects.
Open Locals window by clicking debug menu---
windows ---- Locals (recall that your application must
be in break mode)
22
Error handling is an essential part of any good code.
In Visual Basic 2008 the error mechanism is based
on the concept of exceptions that can be thrown to
raise an error and caught when the error is handled.
If you do not provide any type of error handling and
an error occurs, your user receives a message
about an unhandled exception, which is provided by
the CLR (Common Language Runtime ), and then
the program may terminate, depending on the type
of error encountered.
This is not a user - friendly message and does not
inform the user about the true nature of the error or
how to resolve it.
The unhandled error could also cause users to lose
the data that they were working with or leave the
user and the data in an unknown state.
23
Visual Studio 2008 provides structured error - handling
statements that are common across all languages.
Structured error handling is a way to organize blocks of
code in a structure that handles errors.
Structured error handling in Visual Studio 2008 is
incorporated with the Try . . . Catch . . . Finally block.
You execute the code that might throw an exception in
the Try block, and you handle anticipated errors in the
Catch block.
The Finally block, which is optional, is always executed,
if present, and allows you to place any cleanup code
there regardless of whether an error has occurred.
Therefore, it is important to try to anticipate all possible
errors for the code that is contained in the Try block.

24
Try . . . Catch . . . Finally statement has the following
syntax.
Try
[try statements]
[Exit Try]
Catch exceptionvariable As exceptiontype
[catch statements]
[Exit Try]
[Additional Catch blocks]
Finally
[finally statements]
End Try
Where
The try statements are the statements to be executed that
may cause an error.
25
The exceptionvariable can be any variable name. It will be
set to contain the value of the error that is thrown.
The exceptiontype specifies the exception class type that
the exception belongs to. If this type is not supplied, your
Catch block handles any exception defined in the
System.Exception class. This argument allows you to
specify the type of exception that you maybe looking for. An
example of a specific exception is IOException , which is
used when performing any type of IO (input/output) against
a file.
The catch statements handle and process the error that
has occurred.
The finally statements are executed after all other
processing has occurred.
The optional Exit Try statement allows you to completely
break out of a Try . . . Catch . . . Finally block and resume
execution of code immediately following the Try . . . Catch . . .
Finally block.
26
You can have multiple Catch blocks, meaning that you
can test for multiple errors with different exception types
within the same Try block.
When an error occurs among the try statements, control
is passed to the appropriate Catch block for processing.
When you define a Catch block, you can specify a
variable name for the exception and define the type of
exception you want to catch.
Example
Catch IOExceptionErr As IOException
...
code to handle the exception goes here
...
27
lstData.Items.Add(String variable data:)
Try
If strData.Length > 0 Then
lstData.Items.Add(strData)
End If
Catch nre As NullReferenceException
strData = String now initialized
lstData.Items.Add(strData)
End Try
The error that you want to trap is a NullReferenceException , and that exception is
specified in the Catch block.
When a NullReferenceException occurs, strData variable is initialized to a string
constant and then added the contents of that variable to the list box on your form.
What happened if the following code fragment is executed?
OverFlowException is thrown.
Try
quot = fn / sn
Catch divisionbyzero As Exception
MsgBox(" Division by zero")
End Try
By providing a catch block without a brackets or
arguments, we can catch all exceptions occurred inside a
try block.
Even we can use a catch block with an Exception type
parameter to catch all exceptions happened inside the
try block since in VB.NET, all exceptions are directly or
indirectly inherited from the Exception class.


Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
msgBox("Not executed line")
Catch //Catch e As Exception then in new line msgbox( .)
End Try
msgBox("("Result is {0}", div)
End Sub 'Main
End Class 'MyClient
29
There are two types of exceptions:
Exceptions generated by an executing program and
Exceptions generated by the common language runtime.
System.Exception is the base class for all exceptions in
VB.NET.
Several exception classes inherit from this class
including ApplicationException and SystemException.
These two classes form the basis for most other runtime
exceptions.
Other exceptions that derive directly from
System.Exception include IOException, WebException
etc.
The common language runtime throws
SystemException.
A user program rather than the runtime throws the
ApplicationException.
The SystemException includes the
ExecutionEngineException, StackOverFlowException
etc.
30
It is not recommended that we catch
SystemExceptions nor is it good programming
practice to throw SystemExceptions in our
applications.
System.NullReferenceException
Syste.InvalidCastException
Syste.ArrayTypeMismatchException
System.IndexOutOfRangeException
System.ArithmeticException
System.DevideByZeroException
System.OverFlowException

Você também pode gostar