.NET Fundamentals - PowerPoint PPT Presentation


PPT – .NET Fundamentals PowerPoint presentation | free to download - id: a05e2-OGY2M


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation

.NET Fundamentals


Boxing and Unboxing. Interfaces. 3. C#, Windows Forms Programming, Exceptions. 2 ... What a beautiful day to the console. AppendFormat ... – PowerPoint PPT presentation

Number of Views:43
Avg rating:3.0/5.0
Slides: 147
Provided by: Chip167
Learn more at: http://www.pondviewsoftware.com
Tags: net | fundamentals


Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: .NET Fundamentals

.NET Fundamentals
  • November 13, 2003
  • Week 2

Class 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

  • Common Email List
  • Homework Packaging / winzip project

  • 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

(No Transcript)
Class Goals
Class Goal 1
  • Provide an overview of the .NET Architecture and
    its Major Components
  • Programming Languages
  • Web Services
  • XML Integration

Class Goal 2
  • Understand the .NET Frameworks as an Object
    Oriented, Strongly Typed, Computing Environment

Class 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)
  • Web Services

Class Goals 4
  • Develop a basic fluency programming in C

Course Schedule
(No Transcript)
(No Transcript)
(No Transcript)
Data Types
A 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.

Primitive Types
Primitive Types (continued)
  • 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.

Integer 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)

Defining 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
  • k.ToString()

Floating 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.

  • .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.

Number Formatting
  • Returns a string formatted according to
    instructions contained in a format String
  • double aDbl
  • aDbl.ToString("...") ltlt insert formating

Sample Double Formatting Code
  • double aDbl 1234.567
  • MyStr aDbl(",0.000") ' Returns
  • MyStr aDbl("0.00") ' Returns "1234.57".

Fundamentals of Strings
  • Strings
  • A series of characters treated as a single unit
  • String literals ? How are you?
  • Objects of class String

How 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

Concatenating Strings
  • string strCity Calais
  • string strState ME
  • string strZip 04270
  • string strLoc
  • strLoc strCity , strState
  • strLoc ? Calais, ME 04270

String Functions
  • string strTmp
  • strTmp.Trim() removes leading and trailing
  • strTmp.ToUpper() converts string to all upper
  • strTmp.ToLower() converts string to all lower
  • strTmp.Length returns string length as an
  • strTmp.SubString() extracts a substring

String Function Examples
  • string strTmp Hello World
  • strTmp.Trim()
  • strTmp ? Hello World
  • string strTmp Hello World
  • strTmp.ToLower() ? hello world
  • strTmp.ToUpper() ? HELLO WORLD

String.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.

String.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 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

(No Transcript)
Strings and StringBuilder Class
Strings 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

Using 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.

Create 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!")

Setting 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.

  • 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.

  • 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.

  • 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.

  • 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
  • StringBuilderMyStringBuilder New
    StringBuilder("Hello World!")
  • MyStringBuilder.Insert(6, "Beautiful ")
  • Console.WriteLine(MyStringBuilder)
  • This example displays Hello Beautiful World! to
    the console.

  • 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.

  • 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

Iteration Statements
Iteration statements
  • For loops
  • for (initializers expression iterators)
  • 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

Selection Statements
C - 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)

if / else if / else
  • if (some condition)
  • do something…
  • else if (some other condition)
  • do something…
  • else
  • do something…

(No Transcript)
Jump Statements
  • break
  • continue
  • default
  • goto
  • return

break 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

continue 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

default Statement
  • switch (expression)
  • case constant-expression
  • Statement
  • jump-statement
  • default statement
  • jump-statement

goto 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.

return 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

(No Transcript)
switch 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
  • An default case is often provided to catch any
    cases that do not match the target variable.

C - 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

C - switch Statements
  • This is allowed
  • switch(n)
  • case 0
  • case 1
  • cost 25
  • break …..

C - 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) …

(No Transcript)
C Operators
C Operators
  • Usual slew of operators
  • , -, , /, , - ……
  • Interesting operators
  • new
  • is, as
  • sizeof, typeof
  • checked, unchecked

Creating 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")

(No Transcript)
  • Provide the ability to transfer control within a
  • 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.

  • Defining
  • private void aMethod()
  • insert code here
  • Calling
  • aMethod()

methods with Arguments
  • private void aMethod(string strTmp)
  • …
  • aMethod(hi there)
  • private void aMethod(string strTmp, int iTmp)
  • aMethod(hi there, 4)

methods with Arguments (continued)
  • private void aMethod(string strTmp, int iTmp)
  • …
  • string strTmp Hello World
  • int iTmp 14
  • aMethod(strTmp, iTmp)

methods with return values
  • private bool AnyMethod(string strTmp, int iTmp)
  • …
  • string strTmp Hello World
  • int iTmp 14
  • bool bRet
  • bRet AnyMethod(strTmp, iTmp)

  • 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.

  • 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.

(No Transcript)
Windows Forms
Introduction 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

What 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

What 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

What 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(...)

Windows 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)) ...

Use ToolBox to add Controls to Form
  • Showing the ToolBox
  • Selecting a Control
  • Configuring the Control

Label 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.

Button 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

Using F1 or Search for Help
  • To Use Visual Studio.NET Help function, you can
  • 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

Simple Calculator (Part 1)
RadioButton and GroupBox Control
RadioButtons in a GroupBox
  • 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
  • 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.

GroupBox 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.

Sample 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,

  • ComboBox
  • Combines TextBox features with drop-down list
  • Drop-down list
  • Contains a list from which a value can be
  • Scrollbar appears if necessary

(No Transcript)
Sample 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

Sample 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)
  • bFound True
  • break
  • if (!bFound)
  • ComboBox1.Items.Add(iAdded.ToString)
  • 'ComboBox1.Sorted true

Sample Code To Remove
  • for (int i 0 iltComboBox1.Items.Count i)
  • if (ComboBox1.Items(i)
  • ComboBox1.Items.RemoveAt(i)
  • break
  • iAdded 0

(No Transcript)
The Use of Date and Time
  • DateTime Data Type
  • DateTimePicker and Timer Controls
  • Format and DateDiff Functions

DateTime Data Type
  • DateTime Structure
  • Represents an instant in time, typically
    expressed as a date and time of day.

DateTime 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()

DateTimePicker Control
  • Tool for Selecting a Date
  • Returns Date Selected as a DateTime structure

DateTimePicker 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.

DateTimePicker Sample Code
  • DateTime aDT DateTimePicker1.Value

Timer Control
  • The Windows Forms Timer is a component that
    raises an event at regular intervals. This
    component is designed for a Windows Forms

Timer 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()

TimeSpan Structure
  • TimeSpan ts DateTimePicker2.Value -
  • difHours ts.TotalHours

Clock Class Exercise
(No Transcript)
MessageBox Class
  • Displays a Dialog box that can contain text,
    buttons, and symbols to inform and instruct the

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)

Displays 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.

MessageBox Buttons
MessageBox Icons
DialogResult - 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).
MessageBox Sample Code
  • string strMessage "No server name. Cancel
  • 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
  • Result MessageBox.Show(strMessage, strCaption,
    iBttns , iIcon)
  • ' Gets the result of the MessageBox display. 
  • if (Result DialogResult.Yes)
  • this.Close() ' Closes the parent form. 

Exceptions 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
  • Since exceptions are part of the framework, they
    are consistent across all languages.

Benefits 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,
  • When exceptions do occur, the availability of
    information that will help us locate and fix the
  • You typically get call stack information when
    unhandled exceptions occur.

Evolution of exception handling
  • With Win32, you used error codes and GetLastError
  • HANDLE h CreateFile(………)
  • DWORD d GetLastError()
  • FormatMessage(…d, …)
  • With COM, you used HRESULTS
  • HRESULT hr MyCOMObject.DoSomething()
  • if (FAILED(hr))
  • // handle error

The 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.

Error codes (contd.)
  • Defining your own error codes was a very loose
  • Pick a set of values and put them in a header
  • 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
  • Provide some mechanism for callers to translate
    your codes into meaningful messages.
  • After doing all this, you could still do the
  • CreateFile(………) // ignore all errors
  • OR
  • MyCOMObject.DoSomething() //ignore HRESULT

  • 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

  • In .NET, since all languages are built on the
    runtime, the runtime implements exception
  • 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
  • try
  • catch
  • finally
  • throw

The 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

The 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)

The 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
  • 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.

The catch block
  • You can place multiple catch blocks after a try
  • 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.

The 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

The 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
  • // …
  • finally
  • if (testOut ! null) testOut.Close()

The 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.

Throwing 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.

Throwing 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)

Guidelines 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.

Wrapping 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",

A common mistake
  • Folks commonly put this catch block in their
  • catch (Exception e1)
  • // Do stuff
  • Understand that this assumes you know how to
    handle every kind of exception

Another 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.

Simple Calculator (Part 2) with Exception Handling
(No Transcript)
Tic Tac Toe Program
  • Homework
  • Due
  • November 20, 2003
About PowerShow.com