【发布时间】:2011-05-09 10:15:00
【问题描述】:
我在下面包含了我的源代码草稿。对于我做错了什么,我将不胜感激。我不确定我的语法是否正确......另外,我确实在 Cramster 上找到了一个例子;但我不确定该示例是否按照说明实现了“下标”(如果我错了,请指出)。我还认为“for”循环是相当重复的,因为它似乎建立了与下标应该建立的相同的东西......这段代码是为了响应以下分配:
"编写一个程序,在其中声明一个由五个整数组成的数组并在其中存储五个值 数组。编写一个 try 块,在其中放置一个循环,尝试访问每个 数组的元素,将下标从 0 递增到 10。创建一个 catch 块 捕获最终的 IndexOutOfRangeException;在块内,显示“现在 你已经走得太远了。”屏幕上。将文件另存为 GoTooFar.cs。”
Microsoft® Visual C#® 2008,面向对象编程简介,3e,Joyce Farrell
我的源代码有错误:
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;
}
}
}
}
//我在 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...
}
}
【问题讨论】:
标签: arrays loops exception-handling try-catch