第五讲 C#中的异常处理

*异常类型
每种异常类型都是一个类
两种大分类
System.SystemException
System.ApplicactionException


*.NET中异常处理方式
异常被对象所表现而不是错误代码。
异常的产生是通过throwing一个该异常的对象实现的。
异常的捕获是通过catch该异常的对象。
命名上可以读出是哪类异常:DivideByZeroException
*捕获异常try-catch
当代码段有可能发生异常的时候,我们应该把该代码放置在try中。
捕获到异常后的处理方法放置到catch中。
try
{
 s=//user's input;
 i=int.Parse(s);
}
catch
{
 messageBox.show("Invalid input ,please try again.");
 return;
}
为每个可能的Exception定制解决方法

try
{
 s=//user's input;
 i=int.Parse(s);
}
catch(FormatException)
{
 MessageBox.Show("Please enter a numeric value.");
 return;
}
catch(OverflowException)
{
 MessageBox.Show("Value is too Large/Small!");
 return;
}
catch(Exception ex)
{
 string msg;
 msg=string.Format("Invalid input .\n\n[Error={0}]",ex.Message);
 return;
}
异常处理的系统流程
当程序产生一个异常的时候,它会自动抛出异常,此时.NET进入“异常处理模式”
.NET查找后面是否存在catch子句
if(catch block if found)
 .NEt executes catch & "exception mode" is over
else
 .NET teminates execution

暗示
如果你不想让程序被错误所终止,你要在适当的地方使用try-catch
如果你想让异常处理继续,你要在catch子句中写出一些具体的方法。
空的cactch段相当于给异常放行。
在进行完catch子句后,程序将继续执行除非
return 返回
throw  再次抛出异常
exit   程序退出

try-catch可以嵌套
try
{
 <<Perform operation(s)>>
}
catch(Exception ex)
{
 try
 {
   <<try various recovery strategies>>
 }
 catch
 {
  throw ex;
 }
}

*异常捕获的顺序
必须正确排列捕获异常的catch子句
范围小的Exception放在前面的catch子句
即如果Exception之间有继承关系,把子类放在前面的catch子句中,把父类放到后面的catch子句中。

使用try-catch-finally来确保一些收尾工作。

设计自己的异常
创建独特的异常,使它适合于特定的应用程序
public class TooManyItemsException:Exception
{
 public TooManyItemsException():base(@"You add too many items to

this container.")()
}

public class TooManyItemsTest
{
 public void GenerateException(int i)
 {
  try
   {
    if(i>2) throw new TooManyItemsException();
   }
 }
}

原文地址:https://www.cnblogs.com/iceberg2008/p/1398911.html