12/14/2016 1 Debugging and Error Handling Debugging methods available in the ID Error-handling techniques available in C# Errors Visual Studio IDE reports errors as soon as it is able to detect a problem Syntax errors Language rule violation Syntax error – extraneous semicolon Quick info Error message does not always state the correct problem Run-Time Errors Just because your program reports no syntax errors does not necessarily mean it is running correctly One form of run-time error is a logic error Program runs, but produces incorrect results May be off-by-one in a loop Sometime users enter incorrect values Finding the problem can be challenging Debugging in C# Desk check Many IDEs have Debuggers Debuggers let you observer the run-time behavior You can break or halt execution You can step through the application You can evaluate variables You can set breakpoints Debug menu offers debugging options Debugging in C# (continued) Debug menu options Debugging in C# (continued) Select Start Debugging and number of options to run your program doubles Debug menu options during debugging mode
12
Embed
PowerPoint Presentation · 10/10/2010 · where you want to handle the problem. The catch keyword indicates the catching of an exception. 20 Exception handling C# exception handling
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
12/14/2016
1
Debugging and Error Handling
Debugging methods available in the ID
Error-handling techniques available in C#
Errors
Visual Studio IDE reports errors as soon
as it is able to detect a problem
Syntax errors
Language rule violation
Syntax error – extraneous semicolon
Quick
info
Error message
does not always
state the correct
problem
Run-Time Errors
Just because your program reports no syntax
errors does not necessarily mean it is running
correctly
One form of run-time error is a logic error
Program runs, but produces incorrect results
May be off-by-one in a loop
Sometime users enter incorrect values
Finding the problem can be challenging
Debugging in C#
Desk check
Many IDEs have Debuggers
Debuggers let you observer the run-time
behavior
You can break or halt execution
You can step through the application
You can evaluate variables
You can set breakpoints
Debug menu offers debugging options
Debugging in C# (continued)
Debug menu options
Debugging in C# (continued)
Select Start
Debugging
and number
of options to
run your
program
doubles
Debug menu options during debugging mode
12/14/2016
2
Breakpoints
Markers placed in an application, indicatingthe program should halt execution when itreaches that point
Break mode Examine expressions
Check intermediate results
Use Debug menu to set Breakpoint F9 (shortcut)
Toggles
Breakpoints (continued)
Red glyph placed on the breakpoint line
Breakpoint set
Break Mode
In Break mode, Debugger displays Locals
window
All variables and their values are shown
Locals window at the breakpoint
Break Mode (continued)
Breakpoint location
Debugging in C#
Continue Takes the program out of break mode and
restores it to a run-time mode
If more than one breakpoint set, Continuecauses the program to execute from the haltedline until it reaches the next breakpoint
Stepping through code Execute code line by line and see the
execution path
Examine variable and expression values asthey change
Stepping Through Code
Step Into (F11)
Program halts at the first line of code inside
the called method
Step Over (F10)
Executes the entire method called before it
halts
Step Out (Shift+F11)
Causes the rest of the program statements in
the method to be executed and then control
returns to the method that made the call
12/14/2016
3
Watches
Can set Watch windows during debugging
sessions
Watch window lets you type in one or more
variables or expressions to observe while
the program is running
Watch window differs from Locals window,
which shows all variables currently in scope
Quick Watch option on Debug menu lets you
type a single variable or expressionQuickWatch window
Watches (continued)
Bugs, Errors, and Exceptions
Bugs differ from exceptions Bugs, also called "programmer mistakes," should
be caught and fixed before application released
Errors can be created because of user actions
Example Entering wrong type of data produces unhandled
exception when ParseInt( ) called
Details button in Visual Studio lists a stacktrace of methods with the method that raisedthe exception listed first
Bugs, Errors, and Exceptions
(continued)
Stack
trace
Figure 11-13 Unhandled exception raised by incorrect input string
Exception-Handling Techniques
If event creates a problem frequently, best to
use conditional expressions to catch and fix
problem
Execution is slowed down when CLR has to halt a
method and find an appropriate event handler
Exception-handling techniques are for serious
errors that occur infrequently
Exceptions classes integrated within the FCL
Used with the try…catch…finally program constructs
What is an exception error?
An exception is a problem that arises during
the execution of a program.
A C# exception is a response to an
exceptional situation that arises while a
program is running, such as an attempt to
divide by zero.
18
12/14/2016
4
What is an exception error?
Exceptions provide a way to transfer control
from one part of a program to another.
19
Exception handling
C# exception handling is built upon four
keywords:
try: A try block identifies a block of code for which
particular exceptions will be activated. It's
followed by one or more catch blocks.
catch: A program catches an exception with an
exception handler at the place in a program
where you want to handle the problem. The catch
keyword indicates the catching of an exception.
20
Exception handling
C# exception handling is built upon four
keywords:
finally: The finally block is used to execute a
given set of statements, whether an exception is
thrown or not thrown.
For example, if you open a file, it must be closed
whether an exception is raised or not.
throw: A program throws an exception when a
problem shows up. This is done using a throw
keyword.
21
DEBUGGING IN VS AND VCE
Both VS and VCE(express) allow you to build
applications in two configurations:
Debug (the default) and
Release.
DEBUGGING IN VS AND VCE
In debug configuration and execute it in debug
mode, more is going on than the execution of your
code. Debug builds maintain symbolic information
about your application, so that the IDE knows
exactly what is happening as each line of code is
executed
In release configuration, application code is
optimized. However, release builds also run faster;
and when you have finished developing an
application, you will typically supply users with
release builds because they won’t require the
symbolic information thatdebug builds include
Debug Menu and Toolbar
Breakpoints
12/14/2016
5
Breakpoints
Breakpoints
Toggle Breakpoints On/Off by clicking
in Editor's gray left margin indicator
Debugging in Break Mode
Breakpoints
Monitoring Variable Content
Monitoring variable content is just one
example of how VS and VCE help you a
great deal by simplifying things.
The easiest way to check the value of a
variable is to hover the mouse over its name
in the source code while in break mode.
A yellow tooltip showing information about
the variable appears, including the variable’s
current value.
Viewing Current Values During
Program Execution
Place mouse pointer over variable or
property to view current value
Monitoring Variable Content
Autos (VS only): Variables in use in the
current and previous statements (Ctrl+D, A)
Locals: All variables in scope (Ctrl+D, L)
Watch N: Customizable variable and
expression display (where N is 1 to 4, found
on Debug WindowsWatch)
Immediate and
CommandWindows
The Command (VS only) and Immediate
windows (found on the DebugWindows menu)
enable you to execute commands while an
application is running.
The Command window enables you to perform
VS operations manually (such as menu and
toolbar operations).
The Immediate window enables youto execute
additional code besides the source code lines
being executed, and to evaluate expressions.
12/14/2016
6
Immediate and
CommandWindows
Error-handling techniques
available in C#
Debugging and Error Handling
UNDERSTANDING
EXCEPTIONS
An exception occurs when a program
encounters any unexpected problems.
Your program should be able to handle these
exceptional situations and, if possible,
gracefully recover from them. This is called
exception handling.
STEP BY STEP 3_1
STEP BY STEP 3_1
UNDERSTANDING
EXCEPTIONS
The FCL provides two categories of
exceptions
ApplicationException Represents exceptions
thrown by the applications
SystemException Represents exceptions thrown
by the CLR
12/14/2016
7
try block
A try block contains code that requires common cleanup orexception-recovery operations.
The cleanup code should be put in a single finally block.
The exception recovery code should be put in one or morecatch blocks. Create one catch block for each kind of type you want to handle.
A try block must have at least one catch or finallyblock.
catch block A catch block contains code to execute in response to
an exception.
If the code in a try block doesn’t cause an exception tobe thrown, the CLR will never execute the code in any ofits catch blocks.
You may or may not specify a catch type inparantheses after catch :
The catch type must be of type System.Exception or a typethat derived from System.Exception
If there is no catch type specified, that catch block handles anyexception. This is equivalent to having a catch block thatspecifies System.Exception as a catch type.
CLR searches for a matching catch type from top to bottom.
If CLR cannot find any catch type that matches the exception, CLRcontinues searching up the callstack to find a catch type.
catch block Once the catch block that matches the exception isfound, you have 3 choices:1. Re-throw the same exception, notifying the higher-up call stack
of the exception
2. Throw a different exception, giving richer exception informationto code higher-up in the call stack
3. Let the code continue from the bottom of the catch block
In choices 1-2, an exception is thrown and code startslooking for a catch block whose type matches theexception thrown
In choice 3, the finally block is executed
You can also specify a variable name likecatch(Exception e) to access information specificto the exception.
finally block
The CLR does not completely eliminate memory leaks. Why?
Even though GC does automatic memory clean-up, it only cleansup if there are no references kept on the object.
Even then there may be a delay until the memory is required.
Thus, memory leaks can occur if programmers inadvertently keepreferences to unwanted objects.
C# provides the finally block, which is guaranteed to executeregardless of whether an exception occurs. If the try block executes without throwing, the finally block executes.
If the try block throws an exception, the finally block still executesregardless of whether the exception is caught.
This makes the finally block ideal to release resources fromthe corresponding try block.
finally block Local variables in a try block cannot be accessed in the
corresponding finally block, so variables that must beaccessed in both should be declared before the try block.
Placing the finally block before a catch block is a syntax
error.
A try block does not require a finally block, sometimes noclean-up is needed.
A try block can have no more than one finally block.
Avoid putting code that might throw in a finally block.
Exception handling will still work but the CLR will not keep theinformation about the first exception just thrown in the corresponding tryblock.