在c#中处理错误经常会使用这几个关键字。本文介绍一下其用法
这三个关键字try是必定要用的,要不然就失去了意义。然后catch和finally可以不用但是要注意遵循原则
一个或多个catch的时候可以不用finally但是也可以用。
如果没有catch的时候必须要用finally。
其中每个关键字都对应的有自己的代码块
如这样的形式
try
{
//code
}
catch
{
//code
}
finally
{
//code
}
现在开始说正事了
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());
}
}
C#中的try catch 和finally
最新推荐文章于 2023-12-21 14:02:38 发布