异常概述(Exception)
异常(Exception)
异常是当程序发生错误时产生的一种信号
在.NET中,广泛使用,为什么?
Examples:
divide-by-zero
arithmetic overflow
array access out of bounds
null object reference
file not found
异常类型
每种异常类型都是一个类
两种大分类
System.SystemException
System.ApplicationException
.NET中异常处理方式
.NET中异常处理方式
异常被对象所表现而不是错误代码
异常的产生是通过throwing一个该异常的对象实现的
异常的捕获是通过catch该异常的对象
命名上可以读出是哪类异常:
ArithmeticException, DivideByZeroException, etc.
捕获异常try-catch
当代码段有可能发生异常的时候,我们应该把该代码段放置在try中
捕获到异常后的处理方法放置到catch中。
try
{
s = << user’s input >>;
i = int.Parse(s); // if this fails, .NET throws exception…
}
catch
{
MessageBox.Show(“Invalid input, please try again.”);
return; // return now and give user another chance…
}
更好的解决方案
为每个可能的Exception定制解决方法
try
{
s = << user’s input >>;
i = int.Parse(s); // if this fails, .NET throws exception…
}
catch(FormatException)
{
MessageBox.Show(“Please enter a numeric value.”);
return;
}
catch(OverflowException)
{
MessageBox.Show(“Value is too large/small (valid range ” + int.MinValue +
“ ... ” + int.MaxValue + “).”);
return;
}
catch(Exception ex)
{ // else something we didn’t predict has happened…
string msg;
msg = String.Format(“Invalid input./n/n[Error={0}]”, ex.Message);
MessageBox.Show(msg);
return;
}
异常处理的系统流程