您的位置:首页 > 编程语言 > C#

C#中的try catch 和finally

2015-11-14 16:29 519 查看
  错误的出现并不总是编写应用程序的人的原因,有时应用程序会因为终端用户的操作而发生错误。无论如何,我们都应预测应用程序和代码中出现的错误。

这三个关键字try是必定要用的,要不然就失去了意义。然后catch和finally可以不用但是要注意遵循原则

  一个或多个catch的时间可以不用finally但是也可以用。

  如果没有catch的时间必须要用finally。

  其中每个关键字都对应的有自己的代码块

  try代码块主要包括出错的代码如

   i = Convert.ToInt32(str);

  不知道是否能转化成功。

  catch是处理异常的代码

  finally是处理异常之后要做的事情

  

static void Main(string[] args)
{
int i=1 ;
string str = "dfdfs";
try
{
i = Convert.ToInt32(str);//有异常的地方
}
catch //(Exception e)
{
//Console.WriteLine(e.Message);
i = 3;//处理异常
//throw new Exception("转化失败");
}
/*
这里可以添加上,根据异常的类型来匹配,有点像case。关于异常的类型有很多
//System

ArgumentNullException //参数异常
ArgumentOutOfRangeException //参数异常
DivideByZeroException //除数为0异常
IndexOutOfRangeException //索引超出范围的异常
NullReference-Exception//参数异常
OverflowException //溢出异常
StackOverflowException //堆溢出异常

//System.IO

DirectoryNotFoundException//找不到路径的异常
EndOfStreamException //结束流的异常
FileNotFoundException//找不到文件异常
PathToo-LongException //路径太长异常

//System.Data

DuplicateNameException
InvalidConstrainException
InvalidExpressionException
Missing-PrimaryKeyException
NoNullAllowed-Exception
ReadOnlyException

//System.Runtime.InteropServices

InvalidComObjectException
InvalidOleVariantTypeException
SEHException
catch(ExceptionType e )
{
//异常处理
}
*/
finally
{
Console.WriteLine(i.ToString());

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: