powerpoint presentation · 10/10/2010 · where you want to handle the problem. the catch keyword...
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.
Try Block - General Form
The try Block
try
{
statements that may cause error
}
catch [ExceptionType VariableName ]
{
statements for action when an exception occurs
}
12/14/2016
8
HANDLING EXCEPTIONS
The catch Block
DivideByZeroExceptionArithmeticExceptionOverflowExceptionFormatException
HANDLING EXCEPTIONS
HANDLING EXCEPTIONS HANDLING EXCEPTIONS
The throw Statement
The throw Statement The throw Statement
12/14/2016
9
HANDLING EXCEPTIONS The finally Block: contains code that always executes,
whether or not any exception occurs.
Example 11. class Program {
2. public static void division(int num1, int num2)
3. {
4. float result=0.0f;
5. try
6. {
7. result = num1 / num2;
8. }
9. catch (DivideByZeroException e)
10. {
11. Console.WriteLine("Exception Error !! \n divid by zero !!");
12. // Console.WriteLine("Exception caught: {0}", e);
13. }
14. finally
15. {
16. Console.WriteLine("Result: {0} ", result);
17. }
18. }
19. static void Main(string[] args)
20. {
21. division(10,0);
22. Console.ReadLine();
23. } }50
Example 2
1. catch (DivideByZeroException ex2)
2. {
3. // …..
4. }
5. catch (FormatException ex1)
6. {
7. //……
8. }51
Try
ex1.Message
Try
Exception only
Instead of
DivideByZeroException
Or
FormatException
Practice
52
Use
IndexOutOfRangeException
&
FormatException
&
Exception
VALIDATING USER INPUT
Field-Level Validation
1. Enter (Occurs when a control is entered.)
2. GotFocus (Occurs when a control receives
focus.)
3. Leave (Occurs when focus leaves a control.)
4. Validating (Occurs when a control is validating.)
5. Validated (Occurs when a control is finished
validating.)
6. LostFocus (Occurs when a control looses
focus.)
The Validating Event
Inside the Validating event, you can write code
to do the following:
Programmatically correct any errors or omissions
made by the user.
Show error messages and alerts to the user so
that the user can fix the problem
Use the Focus() method of the control to transfer
the focus back to the field.
Set the Cancel property of CancelEventArgs to
true. This cancels the Validating event, leaving
the focus in the control.
12/14/2016
10
VALIDATING USER INPUT
• 1. KeyDown
• 2. KeyPress
• 3. KeyUp
• The KeyPress event happens after the KeyDown
event but before the KeyUp event
• KeyPress event match keys include any alphabetic
and numeric characters (alphanumeric a–z, A–Z,
and 0–9), not raise this event include Ctrl, Alt, and
the function keys
VALIDATING USER INPUT EXAM private void textBoxAge_KeyPress(object sender,
KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
e.Handled = true;
}
private void textBox1_KeyUp(object sender,
System.Windows.Forms.KeyEventArgs e)
{
if (e.Alt == true)
MessageBox.Show("The ALT key is still down");
}
Methods
Math Class Methods
The Math class
Allows the user to perform common math
calculations
Using methods
ClassName.MethodName( argument1,
arument2, … )
Constants
Math.PI = 3.1415926535…
Math.E = 2.7182818285…
Method Definitions
Writing a custom method
Header
ReturnType Properties Name( Param1, Param2, …)
Body
Contains the code of what the method does
Contains the return value if necessary
For uses call elsewhere in program
Pass parameters if needed
All methods must be defined inside of a class
Method Definitionspublic void MethodName ( )
{
// Contains the code of what the method does
}
public ReturnType methodName(Param1,
Param2, … )
{
//Contains the code of what the method
does
//Contains the return value
}
12/14/2016
11
User-defined method Maximum
public double Maximum( double x, double y, double z )
{
double maximumValue = x;
if ( y > maximumValue )
maximumValue = y;
if ( z > maximumValue )
maximumValue = z;
return maximumValue;
} // end method Maximum
User-defined method Maximum
public void DetermineMaximum()
{
Console.WriteLine( "Enter three floating-point values,\n"
+ " pressing 'Enter' after each one: " );
double number1 = Convert.ToDouble( Console.ReadLine() );
double number2 = Convert.ToDouble( Console.ReadLine() );
double number3 = Convert.ToDouble( Console.ReadLine() );
double result = Maximum( number1, number2, number3 );Console.WriteLine( "Maximum is: " + result );
}
Argument Promotion
Implicit Conversion
Object is converted to a needed type implicitly
Only done if complier knows no data will be lost
Explicit Conversion
Object is manually converted
Required if there could be a loss of data
Widening
Make an object that of a derived class and more complex
Narrowing
Make an object that of a base class and cause some data
loss
Argument PromotionType Can be Converted to Type(s)
bool object
byte decimal, double, float, int, uint, long, ulong, object, short or ushort
sbyte decimal, double, float, int, long, object or short
char decimal, double, float, int, uint, long, ulong, object or ushort
decimal object
double object
float double or object
int decimal, double, float, long or object
uint decimal, double, float, long, ulong, or object
long decimal, double, float or object
ulong decimal, double, float or object
object None
short decimal, double, float, int, long or object
ushort decimal, double, float, int, uint, long, ulong or object
Passing Arguments: Call-By-
Value vs. Call-By-Reference
Passing by value
Send a method a copy of the object
When returned are always returned by value
Set by value by default
Passing by reference
Send a method the actual reference point
Causes the variable to be changed throughout the program
When returned are always returned by reference
The ref keyword specifies by reference
The out keyword means a called method will initialize it
Reference and value
parameters
void SquareRef( ref int x )
{ x = x * x; }
void Square( int x )
{ x = x * x; }
void SquareOut( out int x )
{ x=5;
x = x * x; }
int z=5;
Square ( z );
int z=5;
SquareRef (ref z );
int z;
SquareOut (out z );
Value of z after Square: 5
Value of z after SquareRef: 25
Value of z after SquareOut: 25
12/14/2016
12
Random Number Generation Class Random
Within namespace System
randomObject.Next()
Returns a number from 0 to Int32.MaxValue
Int32.MaxValue = 2,147,483,647
randomObject.Next ( x )
Returns a value from 0 up to but not including x
randomObject.Next ( x, y )
Returns a number between x and up to but not including y
Class Random_ Example
Random rand = new Random();
int value;
value = rand.Next();
// [0; 2,147,483,647]
value = rand.Next( 6 );
// [0; 5]
value = rand.Next( 1, 7 );
// [1,6]