麻烦大家了,帮我看看关于异常的代码!

skyering 2008-09-25 09:15:47
 
static void F()//
{
try
{
G();
}
catch (Exception e)
{
Console.WriteLine("Expection in F:" + e.Message);
e = new Exception("F");
throw;
}
}
static void G()
{
throw new Exception("G");
}
public static void Main()
{
//Expection
try
{
F();
}
catch (Exception e)
{
Console.WriteLine("Expection in G:" + e.Message);
}

}


为什么输出的两个异常信息相同,而不是G、F呢?
...全文
73 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
wartim 2008-09-25
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 skyering 的回复:]
谢谢大家的解释了,尤其是六楼的解释。懂了,throw如果带参,原来的异常就被忽略了。谢了啊!
[/Quote]

catch (Exception e)
{
Console.WriteLine("Expection in F:" + e.Message);
e = new Exception("F"); // 被new了。。
throw e; // 抛的是new的异常"F" 原来的异常就忽略了
}

而如果这样
catch (Exception e)
{
Console.WriteLine("Expection in F:" + e.Message);
throw e; // 抛的是原来的异常
}
就和这样一样了
catch (Exception e)
{
Console.WriteLine("Expection in F:" + e.Message);
throw ; // 抛的是原来的异常
}
skyering 2008-09-25
  • 打赏
  • 举报
回复
谢谢大家的解释了,尤其是六楼的解释。懂了,throw如果带参,原来的异常就被忽略了。谢了啊!
wartim 2008-09-25
  • 打赏
  • 举报
回复
static void F()//
{
try
{
G();
}
catch (Exception e)
{
Console.WriteLine("Expection in F:" + e.Message);
e = new Exception("F"); // e只是包括了异常的一些信息给你看用的,及时你new了是没办法更改异常本身的
throw; // 后面不加默认是抛出已经发生的异常
而如果
throw e; // 强制抛出新new 的异常,原来的异常就忽略掉了,其实在正常的程序里也可以已经用这个来中止一个方法的运行
}
}


skyering 2008-09-25
  • 打赏
  • 举报
回复
e = new Exception("F");
throw;
这个throw,抛出的是哪个异常啊。难道不是e?
wartim 2008-09-25
  • 打赏
  • 举报
回复
要分别显示的话


static void F()//
{
G();
try
{
// F 自己的代码...
}
catch (Exception e)
{
Console.WriteLine("Expection in F:" + e.Message);
throw new Exception("F");
}
}
static void G()
{
throw new Exception("G");
}
public static void Main()
{
//Expection
try
{
F();
}
catch (Exception e)
{
Console.WriteLine("Expection in G:" + e.Message);
}

}


wartim 2008-09-25
  • 打赏
  • 举报
回复

static void F()//
{
try
{
G();
}
catch (Exception e)
{
Console.WriteLine("Expection in F:" + e.Message);
throw new Exception("F");
}
}
static void G()
{
throw new Exception("G");
}
public static void Main()
{
//Expection
try
{
F();
}
catch (Exception e)
{
Console.WriteLine("Expection in G:" + e.Message);
}

}

wartim 2008-09-25
  • 打赏
  • 举报
回复

static void F()//
{
try
{
G();
}
catch (Exception e)
{
Console.WriteLine("Expection in F:" + e.Message);
throw e;
}
}
static void G()
{
throw new Exception("G");
}
public static void Main()
{
//Expection
try
{
F();
}
catch (Exception e)
{
Console.WriteLine("Expection in G:" + e.Message);
}

}
ZengHD 2008-09-25
  • 打赏
  • 举报
回复
因为两次都是调用G();来执行throw new Exception("G");

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧