using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DemoTryCatch
{
class Program
{
static void Main(string[] args)
{
try
{
TestThrow();
}
catch
{
}
}
public static int test1()
{
int i = 1;
try
{
return ++i;
throw new Exception("dfsdfsf");
}
catch (Exception ex)
{
string str = ex.StackTrace;
return i++;
//throw new Exception("dfsdfsf");
}
finally
{
++i;
Console.WriteLine("finally:" + i);
}
}
public static int test2()
{
int i = 1;
try
{
throw new Exception();
}
catch (Exception ex)
{
return ++i;
}
finally
{
++i;
Console.WriteLine("finally:" + i);
}
}
//public static int test3()
//{
// try { }
// finally
// {
// return 1;
// }
//}
///1.不管出没出现异常,finally块中的语句都会执行;
//2.当try或catch块中有return语句时,finally块中的语句仍会执行;
//3.finally块中的语句是在函数返回前执行的,但函数返回值是在finally块中语句执行前确定的;
//4.finally块中不能包含return语句。
//5,(如果该函数要求有返回值)try中也必须要有能够返回函数的调用,比如return ,或者throw excetion(),
// 而且cath中也必须要有能够返回函数的调用,比如return ,或者throw excetion()。
//(相反如果该函数没有返回值,try和cath中的对能够返回函数的调用时不需要的)
class CustomException : Exception
{
public CustomException(string message)
{
}
}
private static int TestThrow()
{
CustomException ex =
new CustomException("Custom exception in TestThrow()");
return 10;
throw ex;
}
//6.这种情况是不会去抓异常的,有点变态。
}
}
本文详细解析了C#中的Try-Catch-Finally结构的使用方式与注意事项,包括异常处理的最佳实践、finally块的功能及其限制条件,并通过具体代码示例展示了如何正确地运用这些结构来增强程序的健壮性和稳定性。
5039

被折叠的 条评论
为什么被折叠?



