Title: .NET Fundamentals
1.NET Fundamentals
2Class Agenda November 13, 2003
- Questions / Homework?
- C
- Windows Forms
- Simple Calculator Class Exercise (part 1)
- More Windows Controls
- Clock Class Exercise
- MessageBox / Exceptions in .NET
- Simple Calculator Class Exercise (part 2)
- Homework Assignment
3Questions?
- Common Email List
- Homework Packaging / winzip project
4Homework
- Add name near or at the top of your code
- your name Homework Week 1 date
- Zip entire project
- I will acknowledge receipt of homework
5(No Transcript)
6Class Goals
7Class Goal 1
- Provide an overview of the .NET Architecture and
its Major Components - Programming Languages
- ADO.NET
- ASP.NET
- Web Services
- XML Integration
8Class Goal 2
- Understand the .NET Frameworks as an Object
Oriented, Strongly Typed, Computing Environment
9Class Goals 3
- Work with various .NET Framework components
- Common Language Runtime (CLR)
- .NET Framework Class Library (FCL)
- Assemblies
- Strong Names
- The Global Assembly Cache (GAC)
- ADO.NET
- ASP.NET
- Web Services
10Class Goals 4
- Develop a basic fluency programming in C
11Course Schedule
Week Topics
1 Introduction to .NET Framework, C
2 C, Windows Forms Programming, Exceptions
3 Introduction to Framework Class Library Types in .NET Objects and Object Construction Boxing and Unboxing Interfaces
12Week Topics
4 ADO.NET (managed data access) - Connections - Adapters - Data Sets - Grid Control
5 Bootstrapping the Common Language Resource (CLR) Modules and Assemblies .Net Packaging Public and Private Keys Shared Assemblies The Global Assemble Cache (GAC) Strong Names
13Week Topics
6 ASP.NET Introduction to Web Services Web Security Advanced Concepts - Serialization - Reflection Web Services Class Project
7 Web Services Class Project (continued)
8 Web Services Class Project (continued)
14(No Transcript)
15C
16Data Types
17A word on types
- All types in .NET derive from System.Object
- They all provide implementations of ToString()
and GetType() - To get a string with the type of any variable,
you can call ltvargt.GetType() - Whenever you call Console.WriteLine(obj) the
ToString() method on obj is implicitly called.
The default ToString implementation for classes
simply returns the name of the class.
18Primitive Types
C Type .NET Framework type
bool System.Boolean
byte System.Byte
sbyte System.Sbyte
char System.Char
decimal System.Decimal
double System.Double
float System.Single
19Primitive Types (continued)
C Type .NET Framework type
int System.Int32
uint System.UInt32
long System.Int64
ulong System.UInt64
object System.Object
short System.Int16
ushort System.UInt16
string System.String
20Boolean
- bool bTmp
- bTmp True
- bool bTmp False
- Boolean variables are stored as 16-bit (2-byte)
numbers, but they can only be True or False. Use
the keywords True and False to assign one of the
two states to Boolean variables.
21Integer Data Types
- Integer variables are stored as signed 32-bit
(4-byte) integers ranging in value from
-2,147,483,648 through 2,147,483,647. - The Integer data type provides optimal
performance on a 32-bit processor, as the smaller
integral types are slower to load and store from
and to memory. (Int32) - Short variables are stored as signed 16-bit
(2-byte) integers ranging in value from -32,768
through 32,767. (Int16) - Long variables are stored as signed 64-bit
(8-byte) integers ranging in value from
-9,223,372,036,854,775,808 through
9,223,372,036,854,775,807. (Int64)
22Defining Integers
- int i
- int i, j, k
- int i 12
- j i ? j is now equal to 12
- i 15
- k i j ? k is equal to 27
- To write an Integer, convert it to a String
using - k.ToString()
23Floating Point Data Types
- Double variables are stored as signed IEEE 64-bit
(8-byte) double-precision floating-point numbers
ranging in value from -1.79769313486231570E308
through -4.94065645841246544E-324 for negative
values and from 4.94065645841246544E-324 through
1.79769313486231570E308 for positive values. - Single variables are stored as signed IEEE 32-bit
(4-byte) single-precision floating-point numbers
ranging in value from -3.4028235E38 through
-1.401298E-45 for negative values and from
1.401298E-45 through 3.4028235E38 for positive
values. Single-precision numbers store an
approximation of a real number.
24Double
- .01, 12345.424, -10.0, 1235000.9999, 125.75
- double dTmp
- dTmp 12.625
- double dTmp 12.625
- Double variables are stored as signed IEEE 64-bit
(8-byte) double-precision floating-point numbers
ranging in value from -1.79769313486231570E308
through -4.94065645841246544E-324 for negative
values and from 4.94065645841246544E-324 through
1.79769313486231570E308 for positive values.
25Number Formatting
- Returns a string formatted according to
instructions contained in a format String
expression. - double aDbl
- aDbl.ToString("...") ltlt insert formating
26Sample Double Formatting Code
- double aDbl 1234.567
- MyStr aDbl(",0.000") ' Returns
"1,234.567". - MyStr aDbl("0.00") ' Returns "1234.57".
27Strings
28Fundamentals of Strings
- Strings
- A series of characters treated as a single unit
- String literals ? How are you?
- Objects of class String
29How do we define strings?
- string strTmp
- strTmp time will tell
- string strTmp time will tell
- strTmp Console.ReadLine()
- string strTmp2
- strTmp2 strTmp
- strTmp2 ? time will tell
30Concatenating Strings
- string strCity Calais
- string strState ME
- string strZip 04270
- string strLoc
- strLoc strCity , strState
strZip - strLoc ? Calais, ME 04270
31String Functions
- string strTmp
- strTmp.Trim() removes leading and trailing
spaces - strTmp.ToUpper() converts string to all upper
case - strTmp.ToLower() converts string to all lower
case - strTmp.Length returns string length as an
integer - strTmp.SubString() extracts a substring
32String Function Examples
- string strTmp Hello World
- strTmp.Trim()
- strTmp ? Hello World
- string strTmp Hello World
- strTmp.ToLower() ? hello world
- strTmp.ToUpper() ? HELLO WORLD
33String.Length Function
- string strTmp
- strTmp in the beginning
- The value of strTmp.Length is 16.
- int i
- i strTmp.Length
- The value of i is 16.
34String.SubString() Function
- String.Substring(startIndex , length )
- Parameters (are Integers)
- startIndex Where the substring starts.
startIndex is zero-based. - length The number of characters in the
substring.
35Substring Examples
- string strTmp
- strTmp around the world
- strTmp.Substring(0,6) ? around
- strTmp.Substring(11,5) ? world
- strTmp.Substring(0,strTmp.Length)
- ? around the world
36(No Transcript)
37Strings and StringBuilder Class
38Strings and StringBuilder Class
- String processing
- Useful in a variety of applications
- String classes (System)
- General string processing, storage
- StringBuilder class (System.Text)
- Facilitates efficient construction of strings
39Using the StringBuilder Class
- The String object is immutable. Every time you
use one of the methods in the System.String
class, you create a new string object in memory,
which requires a new allocation of space for that
new object. In situations where you need to
perform repeated modifications to a string, the
overhead associated with creating a new String
object can be costly. The System.Text.StringBuilde
r class can be used when you want to modify a
string without creating a new object. For
example, using the StringBuilder class can boost
performance when concatenating many strings
together in a loop.
40Create a new instance of the StringBuilder class
- You can create a new instance of the
StringBuilder class by initializing your variable
with one of the overloaded constructor methods,
as illustrated in the following example. - StringBuilder MyStringBuilder new
- StringBuilder("Hello World!")
41Setting the Capacity and Length
- Although the StringBuilder is a dynamic object
that allows you to expand the number of
characters in the string that it encapsulates,
you can specify a value for the maximum number of
characters that it can hold. This value is called
the capacity of the object and should not be
confused with the length of the string that the
current StringBuilder holds. For example, you
might create a new instance of the StringBuilder
class with the string "Hello", which has a length
of 5, and you might specify that the object has a
maximum capacity of 25. When you modify the
StringBuilder, it does not reallocate size for
itself until the capacity is reached. When this
occurs, the new space is allocated automatically
and the capacity is doubled. You can specify the
capacity of the StringBuilder class using one of
the overloaded constructors. The following
example specifies that the MyStringBuilder object
can be expanded to a maximum of 25 spaces.
42- StringBuilder MyStringBuilder new
StringBuilder("Hello World!",5) - Additionally, you can use the read/write Capacity
property to set the maximum length of your
object. The following example uses the Capacity
property to define the maximum object length. -
- MyStringBuilder.Capacity 5
- The EnsureCapacity method can be used to check
the capacity of the current StringBuilder. If the
capacity is greater than the passed value, no
change is made however, if the capacity is
smaller than the passed value, the current
capacity is changed to match the passed value. - The Length property can also be viewed or set. If
you set the Length property to a value that is
greater than the Capacity property, the Capacity
property is automatically changed to the same
value as the Length property. Setting the Length
property to a value that is less than the length
of the string within the current StringBuilder
shortens the string.
43 StringBuilder.methods
Method name Use
StringBuilder.Append Appends information to the end of the current StringBuilder.
StringBuilder.AppendFormat Replaces a format specifier passed in a string with formatted text.
StringBuilder.Insert Inserts a string or object into the specified index of the current StringBuilder.
StringBuilder.Remove Removes a specified number of characters from the current StringBuilder.
StringBuilder.Replace Replaces a specified character at a specified index.
44Append
- The Append method can be used to add text or a
string representation of an object to the end of
a string represented by the current
StringBuilder. The following example initializes
a StringBuilder to "Hello World" and then appends
some text to the end of the object. Space is
allocated automatically as needed. - StringBuilder MyStringBuilder new
StringBuilder("Hello World!") - MyStringBuilder.Append(" What a beautiful day.")
- Console.WriteLine(MyStringBuilder)
- This example displays Hello World! What a
beautiful day to the console.
45AppendFormat
- The AppendFormat method adds text to the end of
the StringBuilder, but also implements the
IFormattable interface and therefore accepts the
standard format strings described in the
formatting section. You can use this method to
customize the format of variables and append
those values to a StringBuilder. The following
example uses the AppendFormat method to place an
integer value formatted as a currency value at
the end of a StringBuilder. - int MyInt 25
- StringBuilder MyStringBuilder New
StringBuilder("Your total is ") - MyStringBuilder.AppendFormat("0C ", MyInt)
- Console.WriteLine(MyStringBuilder)
- This example displays Your total is 25.00 to
the console.
46Insert
- The Insert method adds a string or object to a
specified position in the current StringBuilder.
The following example uses this method to insert
a word into the sixth position of a
StringBuilder. - StringBuilderMyStringBuilder New
StringBuilder("Hello World!") - MyStringBuilder.Insert(6, "Beautiful ")
- Console.WriteLine(MyStringBuilder)
- This example displays Hello Beautiful World! to
the console.
47Remove
- You can use the Remove method to remove a
specified number of characters from the current
StringBuilder, beginning at a specified
zero-based index. The following example uses the
Remove method to shorten a StringBuilder. - StringBuilder MyStringBuilder New
StringBuilder("Hello World!") - MyStringBuilder.Remove(5, 7)
- Console.WriteLine(MyStringBuilder)
- This example displays Hello to the console.
48Replace
- The Replace method can be used to replace
characters within the StringBuilder object with
another specified character. The following
example uses the Replace method to search a
StringBuilder object for all instances of the
exclamation point character (!) and replace them
with the question mark character (?). - StringBuilder MyStringBuilder New
StringBuilder("Hello World!") - MyStringBuilder.Replace("!"c, "?"c)
- Console.WriteLine(MyStringBuilder)
- This example displays Hello World? to the
console.
49Iteration Statements
50Iteration statements
- For loops
- for (initializers expression iterators)
statement - e.g.
- for (int i 1 i lt 5 i)
-
- While loops
- while (expression) statement
- e.g.
- while (ilt5)
-
- expression has to evaluate to boolean.
- Other iteration statements do, foreach
51Selection Statements
52C - Selection Statements
- If statement
- if (expression) statement1 else statement2
- Both statement1 and statement2 themselves can be
if statements - if (a ltb) // has to be used for multiline
// statements -
- Console.WriteLine(Less Than)
- //do something else
-
- else
- Console.WriteLine(Greater Than)
-
53if / else if / else
- if (some condition)
-
- do something
-
- else if (some other condition)
-
- do something
-
- else
-
- do something
-
54(No Transcript)
55Jump Statements
- break
- continue
- default
- goto
- return
56break Statements
- The break statement terminates the closest
enclosing loop or switch statement in which it
appears. Control is passed to the statement that
follows the terminated statement, if any. This
statement takes the following form - break
57continue Statements
- The continue statement passes control to the next
iteration of the enclosing iteration statement in
which it appears. It takes the following form - continue
58default Statement
- switch (expression)
- case constant-expression
- Statement
- jump-statement
- default statement
- jump-statement
-
59goto Statements
- The goto statement transfers the program control
directly to a labeled statement. It takes one of
the following forms - goto identifier goto case constant-expression
goto default where - identifier
- A label.
- constant-expression
- A switch-case label.
60return Statements
- The return statement terminates execution of the
method in which it appears and returns control to
the calling method. It can also return the value
of the optional expression. If the method is of
the type void, the return statement can be
omitted. This statement takes the following form - return expression
61(No Transcript)
62switch Statements
- More Elegant Than the If Else Construct
- Begin with the words Switch followed by the name
of the target variable - For each value or range of values for the target
variable a separate case in listed. - Each case begins with the word case followed by a
specific value or range of values for that case. - Following each case statement is one of more
lines of code to be executed if that case is
true. - An default case is often provided to catch any
cases that do not match the target variable.
63C - switch Statements
- Switch statement
- switch (expression)
- case constant-expression
- statement
- jump-statement
- default statement
- jump-statement
-
- Unlike C and C, a jump statement is required
after a statement fall through not allowed. - Jump statement break, continue, goto, return
64C - switch Statements
- This is allowed
- switch(n)
-
- case 0
- case 1
- cost 25
- break ..
-
65C - switch Statements
- But not this !
- switch(n)
-
- case 0
- Console.WriteLine(Falling through 0)
- case 1
- cost 25
- break
-
- Can switch on strings as well
- case(a)
66(No Transcript)
67C Operators
68C Operators
- Usual slew of operators
- , -, , /, , -
- Interesting operators
- new
- is, as
- sizeof, typeof
- checked, unchecked
69Creating new objects
- A call to new is required to access any
non-static public member. - namespace HelloCall
- class HelloClass
- static void Main(string args)
- Console.WriteLine("In Hello Main")
- HelloClass foo new HelloClass()
- foo.OtherCall()
-
- void OtherCall()
- Console.WriteLine("In OtherCall")
-
-
70(No Transcript)
71methods
72methods
- Provide the ability to transfer control within a
program. - Simplify code sharing, providing an excellent way
to eliminate redundant code. - methods maybe called with one or more arguments
or with no arguments at all - methods maybe called with a return type or a
return type of void to indicate no return type.
73methods
- Defining
- private void aMethod()
-
- insert code here
-
- Calling
- aMethod()
74methods with Arguments
- private void aMethod(string strTmp)
-
- aMethod(hi there)
- private void aMethod(string strTmp, int iTmp)
- aMethod(hi there, 4)
75methods with Arguments (continued)
- private void aMethod(string strTmp, int iTmp)
-
- string strTmp Hello World
- int iTmp 14
- aMethod(strTmp, iTmp)
76methods with return values
- private bool AnyMethod(string strTmp, int iTmp)
-
- string strTmp Hello World
- int iTmp 14
- bool bRet
- bRet AnyMethod(strTmp, iTmp)
77Scope
78Scope
- When a variable is defined the computer assigns
memory to that variable. When the variable is no
longer needed the computer deletes the variable
to free up the memory. Scope defines the time a
variable is available to a program.
79Scope
- A variable defined in a method or in a for
statement will be deleted when the method or for
statement is exited. - Variables that need to persist longer than the
life of the method need to be defined outside the
method , at the class or module level.
80(No Transcript)
81Windows Forms
82Introduction to Windows Forms
- Windows Form
- Using ToolBox to add Controls to Form
- Label Control
- Button
- if else (else if)
- Using F1 or Search for Help
83What Are Controls?
- Controls are things like TextBoxes, Buttons, and
Labels that you use to build a form. - When you create Windows Form project the IDE
provides a blank form. - Controls are added to the form to provide
functionality
84What are properties?
- Forms Have Properties
- Controls Have Properties
- Properties are used to specify controls.
- Text Boxes have Font properties
- Fonts have size and color and bold and
- Labels have a Text property to describe the label
85What About Events?
- When you click on a button the IDE automatically
creates a subroutine where you can write the code
you wish executed when the button is pushed.
This event is called an Click event. - private void button8_Click(...)
86Windows Form
- A Couple of Properties
- ActiveForm ? points to current form
- BackColor Property ? sets background color
- To set a BackColor
- this.BackColor Color.Red
- To Test For a BackColor
- if (this.BackColor.Equals(Color.Red)) ...
-
87Use ToolBox to add Controls to Form
- Showing the ToolBox
- Selecting a Control
- Configuring the Control
88Label Control
- Windows Forms Label controls are used to display
text or images that cannot be edited by the user,
but can be edited dynamically by the programmer. - BackColor defaults to Form
- ForeColor
- Label1.ForeColor Color.White
- Note Font changes must be made directly to the
control on the form.
89Button Control
- The Windows Forms Button control allows the user
to click it to perform an action. - button1.Text Push Me
- button1.BackColor Color.Blue
- button1.ForeColor Color.Yellow
90Using F1 or Search for Help
- To Use Visual Studio.NET Help function, you can
either - Place the cursor on the control or command in
question and type an F1 - or
- Bring up the Help Search Window
- Help ? Search
- Enter the desired topic
91Simple Calculator (Part 1)
92RadioButton and GroupBox Control
93RadioButtons in a GroupBox
94RadioButton
- Windows Forms RadioButton controls present a set
of two or more mutually exclusive choices to the
user. While radio buttons and check boxes may
appear to function similarly, there is an
important difference when a user selects a radio
button, the other radio buttons in the same group
cannot be selected as well. In contrast, any
number of check boxes can be selected. Defining a
radio button group tells the user, "Here is a set
of choices from which you can choose one and only
one." - When a RadioButton control is clicked, its
Checked property is set to true and the Click
event handler is called. The CheckedChanged event
is raised when the value of the Checked property
changes. If the AutoCheck property is set to true
(the default), when the radio button is selected
all others in the group are automatically
cleared. This property is usually only set to
false when validation code is used to make sure
the radio button selected is an allowable option.
The text displayed within the control is set with
the Text property, which can contain access key
shortcuts. An access key allows a user to "click"
the control by pressing the ALT key with the
access key.
95GroupBox Control
- Windows Forms GroupBox controls are used to
provide an identifiable grouping for other
controls. Typically, you use group boxes to
subdivide a form by function. For example, you
may have an order form that specifies mailing
options such as which overnight carrier to use.
Grouping all options in a group box gives the
user a logical visual cue, and at design time all
the controls can be moved easily when you move
the single GroupBox control, all its contained
controls move, too.
96Sample Code
- if (RadioButton1.Checked)
- ...
- else if (RadioButton2.Checked)
- ...
- else if (RadioButton3.Checked)
- ...
- else if (RadioButton4.Checked)
- ...
- Else
-
- MessageBox.Show("No Radio Button Checked!",
"Missing Radio Button", MessageBoxButtons.OK,
MessageBoxIcon.Warning) -
97ComboBox
98ComboBox
- ComboBox
- Combines TextBox features with drop-down list
- Drop-down list
- Contains a list from which a value can be
selected - Scrollbar appears if necessary
99(No Transcript)
100Sample Code To Access Value
- If no value is selected from a ComboBox the value
of ComboBox.Text "" - Otherwise the selected value is in ComboBox.Text
101Sample Code To Insert
- int i
- bool bFound false
- iAdded Label5.Text.Length / 2
- For (int i 0 i lt ComboBox1.Items.Count -
1 i) - If (ComboBox1.Items(i)
iAdded.ToString) - bFound True
- break
-
-
- if (!bFound)
- ComboBox1.Items.Add(iAdded.ToString)
-
- 'ComboBox1.Sorted true
102Sample Code To Remove
- for (int i 0 iltComboBox1.Items.Count i)
- if (ComboBox1.Items(i)
iAdded.ToString) - ComboBox1.Items.RemoveAt(i)
- break
-
-
- iAdded 0
103(No Transcript)
104The Use of Date and Time
- DateTime Data Type
- DateTimePicker and Timer Controls
- Format and DateDiff Functions
105DateTime Data Type
- DateTime Structure
- Represents an instant in time, typically
expressed as a date and time of day. -
106DateTime Member Functions
- Now
- Dim today As DateTime Now
- Year, Month, Day, Hour, Minute, Second
- Dim Year As Integer today.Year
- Dim Minute As Integer DateTime.Now.Minute
- DateTime.Now.ToLongDateString
- Label5.Text DateTime.Now.ToLongDateString()
- DateTime.Now.ToLongTimeString
- Label5.Text DateTime.Now.ToLongTimeString()
107DateTimePicker Control
- Tool for Selecting a Date
- Returns Date Selected as a DateTime structure
108DateTimePicker Control
- The Windows Forms DateTimePicker control allows
the user to select a single item from a list of
dates or times. It appears in two parts a
drop-down list with a date or time represented in
text, and a grid that appears when you click on
the down-arrow next to the list. The grid looks
like the MonthCalendar control, which can be used
for selecting multiple dates. It returns a
DateTime structure.
109DateTimePicker Sample Code
-
- DateTime aDT DateTimePicker1.Value
110Timer Control
- The Windows Forms Timer is a component that
raises an event at regular intervals. This
component is designed for a Windows Forms
environment.
111Timer Control Sample Code
- Timer Properties
- Enabled ? True or False
- Interval ? The number of milliseconds between
each timer tick. The value is not less than one.
To get the number of seconds in the interval,
divide this number by 1,000. - private void Timer1_Tick(object sender,
System.EventArgs e) -
- Label3.Text DateTime.Now.ToLongTimeString()
- Label5.Text DateTime.Now.ToLongDateString()
-
112TimeSpan Structure
- TimeSpan ts DateTimePicker2.Value -
DateTimePicker1.Value - difHours ts.TotalHours
113Clock Class Exercise
114(No Transcript)
115MessageBox
116MessageBox Class
- Displays a Dialog box that can contain text,
buttons, and symbols to inform and instruct the
user.
117 Displays a MessageBox using the Question icon
and specifying the No button as the default.
- Result MessageBox.Show(
- this, _ ? Active Form Optional
- Message, _ ? Message to display
- Caption, ? Caption for MessageBox
- MessageBoxButtons.YesNo, _ ? Buttons
MessageBoxIcon.Question ? Icon)
118Displays a message box with specified text,
caption, buttons, and icon.
- public DialogResult MessageBox.Show(string text,
string caption, MessageBoxButtons buttons,
MessageBoxIcon icon) - Parameters
- text - The text to display in the message box.
- caption - The text to display in the title bar
of the message box. - buttons - One of the MessageBoxButtons values
that specifies which buttons to display in
the message box. - icon - One of the MessageBoxIcon values that
specifies which icon to display in the
message box. - Return Value
- One of the DialogResult values.
119MessageBox Buttons
120MessageBox Icons
121DialogResult - Specifies identifiers to
indicate the return value of a dialog box.
Abort - The return value is Abort (usually sent
from a button labeled Abort). Cancel - The return
value is Cancel (usually sent from a button
labeled Cancel). Ignore - The return value is
Ignore (usually sent from a button labeled
Ignore). No - The return value is No (usually
sent from a button labeled No). None - Nothing is
returned from the dialog box. This means that
the modal dialog continues running. OK - The
return value is OK (usually sent from a button
labeled OK). Retry - The return value is Retry
(usually sent from a button labeled Retry). Yes -
The return value is Yes (usually sent from a
button labeled Yes).
122MessageBox Sample Code
- string strMessage "No server name. Cancel
operation? - string strCaption "No Server Name Specified
- int iBttns MessageBoxButtons.YesNo
- int iIcon MessageBoxIcon.Question
- DialogResult Result
- 'Displays a MessageBox using the Question icon
and specifying the No button as the
default. - Result MessageBox.Show(strMessage, strCaption,
iBttns , iIcon) - ' Gets the result of the MessageBox display.
- if (Result DialogResult.Yes)
-
- this.Close() ' Closes the parent form.
-
123Exceptions
124Exceptions in .NET
- .NET relies heavily on exception handling.
- In fact all error notification/handling by the
framework is in the form of exceptions. - Returning error values by your custom code is
still possible, but not encouraged. - The move from error codes to exceptions will have
an impact on how your code is structured and
designed. - Since exceptions are part of the framework, they
are consistent across all languages.
125Benefits of exception handling
- Cleanup code is kept in a localized spot, and we
can be assured that the code will run. - This implies your logic isnt scattered with a
ton of cleanup code, nor do you have to jump to
cleanup blocks. (On error goto) - Similarly, all code to handle exceptional
situations in kept in a central place. - Once this is done, you write the rest of your
code as if the errors can never occur. - Examples of exceptional situations are arithmetic
overflows, out-of-memory conditions, attempts to
access resources after they have been closed,
etc. - When exceptions do occur, the availability of
information that will help us locate and fix the
error. - You typically get call stack information when
unhandled exceptions occur.
126Evolution of exception handling
- With Win32, you used error codes and GetLastError
- HANDLE h CreateFile()
- if (h INVALID_FILE_HANDLE)
-
- DWORD d GetLastError()
- FormatMessage(d, )
-
- With COM, you used HRESULTS
- HRESULT hr MyCOMObject.DoSomething()
- if (FAILED(hr))
-
- // handle error
-
127The problem with error codes
- What you get back is a 32 bit number, with no
additional information. - FormatMessage normally gave you very generic
error descriptions. (Invalid parameter), with
no indication of where the problem took place. - In order to make sense of error codes, you had to
usually include header files. (So what do you do
for other languages ?). - In the case of smart error codes like HRESULTS,
you were provided with macros that could be used
to decipher the code.
128Error codes (contd.)
- Defining your own error codes was a very loose
process. - Pick a set of values and put them in a header
file. - Take care that the codes do not conflict with
other codes. Usually achieved by starting your
codes at some offset from the well-known set of
codes. - Provide some mechanism for callers to translate
your codes into meaningful messages. - After doing all this, you could still do the
following - CreateFile() // ignore all errors
- OR
- MyCOMObject.DoSomething() //ignore HRESULT
-
-
129Exceptions
- The last example shows how error codes allow you
to opt-in you can opt to handle the error, but
you ignore it by default. - Exceptions change this to the opt-out model you
can explicitly choose to ignore the exception,
but you must handle it by default. - If you dont handle it, your caller gets handed
the exception, and so on up the chain. - When exception handling was added to C, it had
a reputation for being slow. Part of the reason
was that a fairly large burden was placed on the
compiler to make sure cleanup (destruction) code
was put in place whenever an exception could be
thrown.
130Exceptions
- In .NET, since all languages are built on the
runtime, the runtime implements exception
handling. - Unlike error codes, exceptions are objects that
represent exceptional conditions, and can carry a
lot of information. - In C, the following keywords are used with
exceptions. - try
- catch
- finally
- throw
131The try block
- The try block is where you put sections of code
that may potentially throw exceptions. - It also contains code that requires common
cleanup or exception recovery operations. - object o2 new object()
- try
-
- //other code you may have
- int i2 (int) o2 // Error
-
- A try-block by itself is no good it must be
associated with at least one catch or finally
block.
132The catch block
- A catch block contains code to execute in
response to an exception. - A try block can have zero or more catch blocks
associated with it. - object o2 new object()
- try
-
- //other code you may have
- int i2 (int) o2 // Error
-
- catch (InvalidCastException e)
-
- // exception handling code
- Console.WriteLine(Invalid cast exception)
133The catch block
- If the code in the try block doesnt cause an
exception to be thrown, the CLR never executes
any code contained within the catch blocks. - The thread skips over the catch blocks and
executes code in the finally block (if one
exists.) - Any statements following the catch/finally blocks
are executed - The expression in the parentheses after the catch
keyword is called an exception filter. In C the
exception filter has to be an object of the type
System.Exception or a derivative.
134The catch block
- You can place multiple catch blocks after a try
block. - The catch blocks are searched from top to bottom.
- Important Place the more specific exceptions at
the top, in the order you would like them caught. - The C compiler does generate a compile error if
more general catch blocks are placed ahead of the
more specific ones.
135The catch block
- If none of the catch blocks match the exception
that occurred, the CLR continues up the call
stack looking for one. - If none are found after reaching the top of the
call stack, an unhandled exception is reported. - Within a catch block, after any handler code you
write, you can - Rethrow the same exception.
- Throw a different exception.
- Just fall out of the bottom.
- Code in a finally block (if present) is always
executed.
136The finally block
- A finally block contains code that is guaranteed
to execute. - Typically contains cleanup code required by the
actions taken in the try block. - A finally block is associated with a try block.
(I.e. no catch block is required). - try
- StreamWriter testOut new StreamWriter(_at_"output
.txt",true) - //
-
- finally
- if (testOut ! null) testOut.Close()
-
137The System.Exception Class
- This class is the base class for all exceptions.
- Interesting members
- Message a string that contains a description of
the exception. - Source the name of the application or object
that caused the error - StackTrace a string representation of the stack
trace at the time the exception was thrown.
138Throwing an exception
- Within a catch block, we can choose to rethrow
the same exception, or throw a new one. - try
-
- //other code you may have
- int i2 (int) o2 // Error
-
- catch (InvalidCastException e1)
-
- Console.WriteLine("Invalid cast exception")
- throw // rethrow the exception
-
- catch (NullReferenceException e1)
-
- Console.WriteLine("Null reference exception")
- throw new Exception("New exception") //throw
new ex. -
-
139Throwing an ApplicationException
- try
-
- if ((textBox1.Text "") (textBox2.Text
"")) -
- throw new System.ApplicationException("Values
must be numeric.") -
-
- catch (ApplicationException ex)
-
- MessageBox.Show(ex.Message)
-
- catch (Exception ex)
-
- MessageBox.Show(ex.Message)
-
140Guidelines for exception handling
- Catch the most specific exception possible
- Otherwise, you may end up handling exceptions you
did not intend to. - Catch the exception only if you are absolutely
sure how to handle it. - Order your exception blocks carefully. Remember,
catch blocks are executed sequentially. - Finally blocks are a good place to put cleanup
code. Try not to put code that may throw
exceptions in the finally block. (If it does, the
application will not crash, the exception will
just be passed up the call chain.) - Return values still have their place do not use
exceptions to return normal error conditions.
141Wrapping an exception
- A lot of times, you just want to add more
descriptive information to the exception you are
handling. In this case, you can wrap the
exception that was just caught. InnerException
will contain the original exception. -
- object o2 new object()
- try
-
- int i2 (int) o2 // Error
-
- catch (InvalidCastException e1)
-
- Console.WriteLine("Invalid cast exception")
- throw new InvalidCastException("My own info",
e1) -
142A common mistake
- Folks commonly put this catch block in their
code - catch (Exception e1)
-
- // Do stuff
-
- Understand that this assumes you know how to
handle every kind of exception
143Another common mistake
- In one of the earlier slides, we did this
- catch (NullReferenceException e1)
-
- Console.WriteLine("Null reference exception")
- throw new Exception("New exception") //throw
new ex. -
- This is generally a bad idea since we caught a
more specific exception and replaced it with one
that has less information.
144Simple Calculator (Part 2)withException Handling
145(No Transcript)
146Tic Tac Toe Program
- Homework
- Due
- November 20, 2003