Intro Week 4

esse quam videri
Jump to: navigation, search

Try and Catch

Another branching statement used to catch runtime errors.

Try and catch is useful when you are going to do something that may cause a run time error. These errors may occur when

  • Parsing user input
  • Converting Datatypes
  • Trying to connect to a remote server
  • Connecting to a database

For example consider a program that asks the user what their favorite number is.

using System;
using System.Collections.Generic;
using System.Text;

namespace FavoriteNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            int intFavNumber;
            string strFavNumber;
            
            Console.Write("What is you favorite number?");
            strFavNumber = Console.ReadLine();

            intFavNumber = Int16.Parse(strFavNumber);

        }
    }
}

if you type 'monkey' for your favorite number the program crashes with the folling message


Unhandled Exception: System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolea
n parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Int16.Parse(String s, NumberStyles style, NumberFormatInfo info)
   at FavoriteNumber.Program.Main(String[] args)

This program can be fixed be using a try and catch

try
{
	//some crazy code that may cause errors
}
catch (Exception e)
{
    string strError = e.ToString();
}

Looping Statements

  • for
  • while
  • do... while
  • foreach (we'll do this after we do arrays)

for

syntax

    for ([initializers]; [expression]; [iterators]) statement
    
for (int i=0; i < 10; i++)
{
    Console.WriteLine("For Loop " + i + "<br />");
}

Produces

For Loop 0
For Loop 1
For Loop 2
For Loop 3
For Loop 4
For Loop 5
For Loop 6
For Loop 7
For Loop 8
For Loop 9
for (int i=0; i < 20; i++)
{
    if (i == 10)
            break;

    if (i % 2 == 0)
            continue;

    Console.WriteLine( "For Loop " + i + "<br />");
}

Produces

For Loop 1
For Loop 3
For Loop 5
For Loop 7
For Loop 9

For loops can also be good to dynamically add or alter the contents or web controls. For example If I wanted a web control to have 100 items in it like this . I could use a for loop to add them here's an example

/infod/jeff/classSource/class3/DynamicAddDropdown.aspx - source

while

while syntax

  while (expression) statement
int MyInt = 0;   //iterator for while loop

while (MyInt < 10)
{
    Console.WriteLine("While Loop " + MyInt + "\n");
    MyInt++;
}

produces

While Loop 0
While Loop 1
While Loop 2
While Loop 3
While Loop 4
While Loop 5
While Loop 6
While Loop 7
While Loop 8
While Loop 9

do

do... while syntax

   do statement while (boolean-expression);
   
int myIntDo = 0;  //iterator for do loop

do
{
    Console.WriteLine("do Loop " + myIntDo + "\n");
    myIntDo++;
}       while (myIntDo < 10);   //Check interator

produces

do Loop 0
do Loop 1
do Loop 2
do Loop 3
do Loop 4
do Loop 5
do Loop 6
do Loop 7
do Loop 8
do Loop 9


string doLoopResult2 = "";
int myIntDo2 = 30;
do
{
        doLoopResult2 +="do Loop " + myInt + "\n";
        myIntDo2++;
}	while (myIntDo2 < 10);

produces do Loop 30

Notice the do loop always executes once as it doesn't check the iterator until after execution.

Random r = new Random();    //Get a new Random Object
            
//Choose a number between 1 and 10
int randNunberBetweenOneandTen = r.Next(10) + 1;

//Write the random number
Console.WriteLine(randNunberBetweenOneandTen);

Home Work

Guessing Game with a while loop where the program guesses a random number.

It should then ask the user to guess the number. If the number is correct say you win. If the guess is incorrect tell the user if the random number is higher or lower and allow then to guess again.

1 extra point for counting and displaying the number of guesses.