Week 7 : Debugging and Error Handling
-
Upload
holmes-vang -
Category
Documents
-
view
38 -
download
1
description
Transcript of Week 7 : Debugging and Error Handling
C#4.0Week 7:
Debugging and Error Handling
Debugging methods available in the ID Error-handling techniques available in C#
C#4.0
Debugging methods available in the ID
Week 7: Debugging and Error Handling
C#4.0
DEBUGGING IN VS AND VCE
Both VS and VCE(express) allow you to build applications in two configurations: Debug (the default) and Release.
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 3
C#4.0
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
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 4
C#4.0
Outputting Debugging Information
First, an additional using directive appears at the beginning of the code: using System.Diagnostics;
Then Debug.WriteLine() Trace.WriteLine()
System.Diagnostics.Debug.WriteLine("Bananas");
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 5
C#4.0
Debug Menu and Toolbar Breakpoints
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 6
C#4.0
Breakpoints Breakpoints
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 7
Toggle Breakpoints On/Off by clicking in Editor's gray left margin indicator
C#4.0
Debugging in Break Mode Breakpoints
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 8
C#4.0
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.
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 9
C#4.0
Viewing Current Values During Program Execution
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 10
Place mouse pointer over variable or property to view current value
C#4.0
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)
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 11
C#4.0
Locals window
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 12
C#4.0
The Watch window
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 13
C#4.0
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.
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 14
C#4.0
Immediate and CommandWindows
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 15
C#4.0
Error-handling techniques available in C#
Week 7: Debugging and Error Handling
C#4.0
Slide 17
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.
C#4.0
Slide 18
STEP BY STEP 3_1
C#4.0
Slide 19
STEP BY STEP 3_1
C#4.0
Slide 20
UNDERSTANDING EXCEPTIONS
The FCL provides two categories of exceptions ApplicationException Represents exceptions
thrown by the applications SystemException Represents exceptions thrown
by the CLR
C#4.0
Slide 21
Try Block - General Form
The try Block
Try{
statements that may cause error}catch [ExceptionType VariableName ]{
statements for action when an exception occurs}
C#4.0
Slide 22
HANDLING EXCEPTIONS The catch Block
DivideByZeroExceptionArithmeticExceptionOverflowExceptionFormatException
C#4.0
Slide 23
HANDLING EXCEPTIONS
C#4.0
Slide 24
HANDLING EXCEPTIONS
C#4.0
Slide 25
HANDLING EXCEPTIONS The throw Statement
C#4.0
Slide 26
The throw Statement
C#4.0
Slide 27
The throw Statement
C#4.0
Slide 28
HANDLING EXCEPTIONS The finally Block: contains code that always executes,
whether or not any exception occurs.
C#4.0
Slide 29
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.)
C#4.0
Slide 30
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.
C#4.0
Slide 31
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
C#4.0
Slide 32
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");
}
C#4.0
Slide 33
The CausesValidation Property
The default value of the CausesValidation property for a control is true for all controls
When you want a control to respond, regardless of the validation status of other controls, you should set the CausesValidation property of that control to false
C#4.0
Slide 34
9:06:37 AM
The ErrorProvider Component
The ErrorProvider component can set a small icon next to a field when it contains an error
When the user moves the mouse pointer over the icon, an error message pops up as a ToolTip
C#4.0
Slide 35
9:06:37 AM
The ErrorProvider Component
C#4.0
Slide 36
Using the ErrorProvider Component andOther Validation Techniques
C#4.0
Slide 37
The Validating Event and Sticky Form
The CausesValidation property of the btnExit control to false.
Declare the following variable outside a method block in the class:
private bool closingFlag = false; Add the following code to the Click event handler of the
Exit button:
C#4.0
Slide 38
The Validating Event and Sticky Form
Attach the following event handling code to the Validating events of both the txtMile controls
C#4.0
Methods
C#4.0
Slide 40
Math Class Methods The Math class
Allows the user to perform common math calculations
Using methodsClassName.MethodName( argument1,
arument2, … ) Constants
Math.PI = 3.1415926535…Math.E = 2.7182818285…
C#4.0
Slide 41
Math Class Methods
Method Example Abs( x ) Abs( 23.7 ) is 23.7
Ceiling( x ) Ceiling( 9.2 ) is 10.0 Ceiling( -9.8 ) is -9.0
Cos( x ) Cos( 0.0 ) is 1.0
Exp( x ) Exp( 1.0 ) is approximately 2.7182818284590451
Floor( x ) Floor( 9.2 ) is 9.0 Floor( -9.8 ) is -10.0
Log( x ) Log( 2.7182818284590451 ) is approximately 1.0
Max( x, y ) Max( 2.3, 12.7 ) is 12.7 Max( -2.3, -12.7 ) is -2.3
Min( x, y ) Min( 2.3, 12.7 ) is 2.3 Min( -2.3, -12.7 ) is -12.7
C#4.0
Slide 42
Math Class Methods
Method Example Pow( x, y ) Pow( 2.0, 7.0 ) is 128.0
Pow( 9.0, .5 ) is 3.0 Sin( x ) Sin( 0.0 ) is 0.0 Sqrt( x ) Sqrt( 900.0 ) is 30.0
Sqrt( 9.0 ) is 3.0 Tan( x ) Tan( 0.0 ) is 0.0
C#4.0
Slide 43
9:06:37 AM
Method Definitions
Writing a custom method HeaderReturnType 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
C#4.0
Slide 44
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 }
C#4.0
Slide 45
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
C#4.0
Slide 46
9:06:37 AM
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 ); }
C#4.0
Slide 47
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
C#4.0
Slide 48
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
C#4.0
Slide 49
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
C#4.0
Slide 50
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
C#4.0
Slide 51
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
C#4.0
Slide 52
Class Random_ ExampleRandom rand = new Random();
int value;
value = rand.Next();
// phát sinh 1 số trong [0; 2,147,483,647]value = rand.Next( 6 );
// phát sinh 1 số trong [0; 5]
value = rand.Next( 1, 7 );
// phát sinh 1 số trong [1,6]
C#4.0
Finish
Windows Programming 1 Chapter 7: Debugging and Error Handling Slide 53