try catch嵌套之后出现异常执行顺序:

static void Main(string[] args)
{
try
{
Console.WriteLine("----------------------外层try------------------------------");
errorMethod();
}
catch (Exception ex)
{
Console.WriteLine("----------------------外层catch" + ex.Message + "------------------------------");
}
finally {
Console.WriteLine("----------------------外层finally------------------------------");
} Console.ReadKey(); } private static void errorMethod()
{
try
{
Console.WriteLine("----------------------内层try------------------------------");
int i = ;
int a = /i;
}
catch (Exception ex)
{
Console.WriteLine("----------------------内层catch" + ex.Message + "------------------------------");
}
finally {
Console.WriteLine("----------------------内层finally------------------------------");
}
}

输出结果:C# try catch嵌套-LMLPHP

内层catch处理了异常,所以没有执行外层catch,把内层的catch注释掉,再试下:

static void Main(string[] args)
{
try
{
Console.WriteLine("----------------------外层try------------------------------");
errorMethod();
}
catch (Exception ex)
{
Console.WriteLine("----------------------外层catch" + ex.Message + "------------------------------");
}
finally {
Console.WriteLine("----------------------外层finally------------------------------");
} Console.ReadKey(); } private static void errorMethod()
{
try
{
Console.WriteLine("----------------------内层try------------------------------");
int i = ;
int a = /i;
}
//catch (Exception ex)
//{
// Console.WriteLine("----------------------内层catch" + ex.Message + "------------------------------");
//}
finally {
Console.WriteLine("----------------------内层finally------------------------------");
}
}

输出结果:C# try catch嵌套-LMLPHP

总结:try catch嵌套,内层不能捕获时,会考虑外层内否捕获,内层能捕获,则外层catch不执行。

05-17 09:17