C#复习(十三)异常
- 程序运行期间发生错误称为异常。在C# 中用类的形式将不正常的情况进行了封装和描述,描述不正常的类就叫做异常类。C#对所有描述问题的类进行共性的向上抽取,最终形成一个父类叫做Exception.
- 分为SystemException和ApplicationException(用户自定义异常)。
- 实现自定义异常类要继承ApplicationException。
class MyException :
ApplicationException
{
public MyException(string s):base(s)
{
}
}
class Program
{
public void Show(int[] array, int index)
{
if (index
> array.Length)
{
throw new
IndexOutOfRangeException("索引越界");
}
if (index
< 0)
{
throw new
MyException("索引不能为负数");
}
Console.WriteLine(array[index]);
}
static void Main(string[] args)
{
Program p
= new Program();
int[]
array = { 1, 2, 3, 4, 5 };
p.Show(array, -2);
}
}
- try-catch-finally:try块的代码是程序中可能出现错误的操作部分,一旦有异常则抛给catch;catch块的代码块用来处理各种错误的部分(可以有多个),必须正确排列捕获异常的catch子句,如果Exception之间存在继承关系,就应把子类的Exception放在前面的catch子句中;finally代码可以省略,且无论是否产生异常,finally块都会执行。
- 当要catch自定义异常类时,需先抛出,才能捕获。
- 有catch{}时,可以没有finally{},没有catch{}时,必须有finally{}
static void Main(string[] args)
{
Program p
= new Program();
int[]
array = { 1, 2, 3, 4, 5 };
p.GetValueAndAverage(array, -1);
Console.ReadLine();
}
public int GetValue(int[] array, int
index)
{
if (index
> array.Length)
{
throw new
IndexOutOfRangeException("索引越界");
}
if (index
< 0)
{
throw new
MyException("索引不能为负数");
}
return
array[index];
}
public void GetValueAndAverage(int[] array,int
index)
{
int sum =
0;
float
average = 0;
float
value = 0;
for (int i
= 0; i < array.Length; i++)
{
sum += array[i];
}
try
{
int length =
array.Length;
average = sum/length;
value =
GetValue(array, index);
}
catch (MyException myEx)
{
Console.WriteLine(myEx.Message);
}
catch
(DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
catch
(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Sum:" +
sum);
Console.WriteLine("Average:"
+ average);
Console.WriteLine("Value:" +
value);
}
}