c#中异常问题

来源:百度知道 编辑:UC知道 时间:2024/06/02 23:02:55
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ThrowExample
{
class Program
{
private static double average(double[] scores)
{
double sum = 0;
for (int i = 0; i < scores.Length; i++)
{
double score = scores[i];
if (score > 100 || score < 0)
{
throw new ArgumentOutOfRangeException("学生成绩","学生成绩必须在0~100之间");
sum += score;
}
return sum / scores.Length;
}
}
private static double[] parseCSV(string text)
{
if (string.IsNullOrEmpty(text))
{
throw new ArgumentOutOfRangeException("text", "parseCSV方法参数不能为NULL或者空字符串"

错误的意思是说,ThrowExample.program.average () 函数中,不是所有的代码路径都提供了返回值,比如:
int foo (int i)
{
if (i > 0)
return i ;
}

这个函数中,if 条件满足,则返回i,但不满足是没有返回。

具体到你的代码,还挺隐蔽,
private static double average(double[] scores)
{
double sum = 0;
for (int i = 0; i < scores.Length; i++)
{
double score = scores[i];
if (score > 100 || score < 0)
{
throw new ArgumentOutOfRangeException("学生成绩","学生成绩必须在0~100之间");
sum += score;
}
return sum / scores.Length;
}
}

实际上return 应该在for 循环外面,sum += score应该在if 的外面。

你把异常抛出来了 所以没有返回值 但你的函数是有返回值 建议你不要抛出异常 或者不管异常 界面层捕获

打断点调试一下,肯定是你返回的类型有问题