I have included my source code draft below. I would appreciate any input on what I’m doing incorrectly. I’m not sure my syntax is correct… Also, I did find an example on Cramster; but I’m not sure that the example implemented the “subscript” as directed (please point it out if I am wrong in this) by the instructions. I also think that the “for” loop is rather repetitive since it appears that it’s establishing the same thing that the subscript is supposed to establish… This code is in response to the following assignment:
“Write a program in which you declare an array of five integers and store five values in
the array. Write a try block in which you place a loop that attempts to access each
element of the array, incrementing a subscript from 0 to 10. Create a catch block that
catches the eventual IndexOutOfRangeException; within the block, display “Now
you’ve gone too far.” on the screen. Save the file as GoTooFar.cs.”
Microsoft® Visual C#® 2008, An Introduction to Object-Oriented Programming, 3e, Joyce Farrell
My source code with errors:
using System;
namespace Further
{
public class GoTooFar
{
public static void Main()
{
private static int[] fiveIntArray = {1, 2, 3, 4, 5};
//private static int CUTOFF = 11;
int subscript;
int rate;
try
{
//bool further;
//public static int DetermineArray(int further)
for(int x = 0; x < 10; x++)
if(further < 11)
throw new IndexOutofRangeException("Now you've gone too far.");
subscript = 0;
else
subscript = 10;
rate = fiveIntArray[subscript];
return rate;
}
catch(IndexOutOfRangeException e)
{
throw;
Console.WriteLine(e.StackTrace);
//Console.WriteLine("Now you've gone too far.");
//return e;
}
}
}
}
//The example I found on Cramster.com:
using System;
namespace Console2
{
class Class1
{
static void Main(string[] args)
{
int[] numbers = new int[5] {1, 2, 3, 4, 5};
try
{
for(int i=0;i<10;i++)
if(i>5)
throw new IndexOutOfRangeException("Now you’ve gone too far.");
}
catch(IndexOutOfRangeException e)
{
throw;
}
}//end ma...
}
}
You’re not supposed to throw an exception, just catch the one the runtime throws. There are several other issues:
private static.It can be as simple as:
Note, we don’t actually use
rate. It’s just there so it will be a valid statement.