在使用NH时,如果定义一个类的方法,须定义成virtual类型,这样才可以让NH自动产生代理类来调用此方法.但这时,有一个问题:如果我们这个方法中抛出了自己定义的异常,在外面会能得到自己的异常吗?
public class People
{
public virtual void Eat(string food)
{
if (foot == "")
throw new ArgumentException();
if (foot == "水")
throw new BusinessException();
}
public static void ShowMessage(string message)
{}
public static void TestEatException()
{
try
{
this.Eat("水");
}
catch (ArgumentException)
{
ShowMessage("没有东西吃");
}
catch (BusinessException)
{
ShowMessage("水应该不能吃,酒还说得过去");
}
catch(Exception exp)
{
ShowMessage("不应该出现这种异常的" + exp.GetType().Name);
}
}
}
{
public virtual void Eat(string food)
{
if (foot == "")
throw new ArgumentException();
if (foot == "水")
throw new BusinessException();
}
public static void ShowMessage(string message)
{}
public static void TestEatException()
{
try
{
this.Eat("水");
}
catch (ArgumentException)
{
ShowMessage("没有东西吃");
}
catch (BusinessException)
{
ShowMessage("水应该不能吃,酒还说得过去");
}
catch(Exception exp)
{
ShowMessage("不应该出现这种异常的" + exp.GetType().Name);
}
}
}
想想TestEatException会出现什么异常?刚开始时,我以为是"水应该不能吃,酒还说得过去",但我错了.
正确结果是"不应该出现这种异常TargetInvocationException".想来也是NH的反射搞得鬼.
但如果我们调试一下,发现异常的InnerException是我们自定义的期望抛出来的异常.哈哈.
临时解决方法如下:
public class People
{
public virtual void Eat(string food)
{
if (foot == "")
throw new ArgumentException();
if (foot == "水")
throw new BusinessException();
}
public static void ShowMessage(string message)
{}
public static void TestEatException()
{
try
{
try
{
this.Eat("水");
}
catch (TargetInvocationException exp)
{
if (exp.InnerException != null)
throw exp.InnerException;
}
}
catch (ArgumentException)
{
ShowMessage("没有东西吃");
}
catch (BusinessException)
{
ShowMessage("水应该不能吃,酒还说得过去");
}
catch (Exception exp)
{
ShowMessage("不应该出现这种异常的" + exp.GetType().Name);
}
}
}
{
public virtual void Eat(string food)
{
if (foot == "")
throw new ArgumentException();
if (foot == "水")
throw new BusinessException();
}
public static void ShowMessage(string message)
{}
public static void TestEatException()
{
try
{
try
{
this.Eat("水");
}
catch (TargetInvocationException exp)
{
if (exp.InnerException != null)
throw exp.InnerException;
}
}
catch (ArgumentException)
{
ShowMessage("没有东西吃");
}
catch (BusinessException)
{
ShowMessage("水应该不能吃,酒还说得过去");
}
catch (Exception exp)
{
ShowMessage("不应该出现这种异常的" + exp.GetType().Name);
}
}
}
这时就会出现"水应该不能吃,酒还说得过去"的信息了.如果您有更好的办法,一定要分享呀!