异常概述exception 捕获异常及处理 跟踪trace
异常是当程序发生错误时产生的一种信号
异常的类型
每种异常类型都是一个类
两种大分类
system.systemException
system.applicationexception
处理方式
1异常被对象所表现而并不是错误代码
2异常的产生是通过throwing一个该异常的对象实现的
3异常的捕获是通过catch该异常的对象
4命名上可以读出是哪类异常
捕获异常try- catch
把可能发生异常的代码放到try中
用catch 得到结果
为每个可能的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;
}
异常处理的系统流程
1自动抛出异常
2暗示
try -catch工作方式
1 无异常就跳过catch
2 异常时进入catch段
try
{
step1;
step2;
step3;
}
catch (Exception ex)
{
catch1;
catch2;
}
step4;
暗示
在进行catch子句后程序继续执行
除非catch中有return throw exit
可以嵌套
try
{
<< perform operation(s) >>
}
catch(Exception ex)
{
try
{
<< try various recovery strategies >>
}
catch
{
// none of the strategies worked…
throw ex;
}
}
异常捕获顺序
1 范围小的Exception放在前面
2如果Exception之间有继承关系,则把子类放在
前面的Exception子句中,把父类放在后面的catch中
try-catch-finally来确保一些收尾工作
finally{《close database》}
Throw Exception
跟踪Tracing
运行错误时输出信息
配置跟踪
<configuration>
<appSettings>
<add key="Traing" value="true">
</appSettings>
</configuration>
using T = System.Diagnostics.Trace;
public class DataAccess
{ ...
public void Open()
{
try {
T.WriteLineIf(Globals.Trace, “DataAccess.Open():”);
T.Indent();
T.WriteLineIf(Globals.Trace, “Connection string=...”);
...
}
catch(Exception ex) {
T.WriteLineIf(Globals.Trace, ex.GetType() + “: ” + ex.Message);
T.WriteLineIf(Globals.Trace, ex.StackTrace);
...
}
finally {
T.Unindent();
T.Flush();
}
}