刚看到蜗牛的帖子• 嵌套异常处理 开发人员喜欢在方法的末尾加上异常处理的嵌套方法,如:
C# codepublic class NestedExceptionHandling
{
public void MainMethod()
{
try
{
//some implementation
ChildMethod1();
}
catch (Exception exception)
{
//Handle exception
}
}private void ChildMethod1()
{
try
{
//some implementation
ChildMethod2();
}
catch (Exception exception)
{
//Handle exception
throw;}
}private void ChildMethod2()
{
try
{
//some implementation
}
catch (Exception exception)
{
//Handle exception
throw;
}
}
}
如果相同的异常被处理多次,上面的代码会发生什么?毫无疑问,性能开销将会剧增。 解决办法是让异常处理方法独立出来,如:
C# codepublic class NestedExceptionHandling
{
public void MainMethod()
{
try
{
//some implementation
ChildMethod1();
}
catch(Exception exception)
{
//Handle exception
}
}private void ChildMethod1()
{
//some implementation
ChildMethod2();
}private void ChildMethod2()
{
//some implementation
}
}我想问的是:在三层架构中,是不是应该只有UI层才需要Try..Catch?
理由:因为DAL,BLL中的异常都可以通过UI层的调用捕捉到异常。
C# codepublic class NestedExceptionHandling
{
public void MainMethod()
{
try
{
//some implementation
ChildMethod1();
}
catch (Exception exception)
{
//Handle exception
}
}private void ChildMethod1()
{
try
{
//some implementation
ChildMethod2();
}
catch (Exception exception)
{
//Handle exception
throw;}
}private void ChildMethod2()
{
try
{
//some implementation
}
catch (Exception exception)
{
//Handle exception
throw;
}
}
}
如果相同的异常被处理多次,上面的代码会发生什么?毫无疑问,性能开销将会剧增。 解决办法是让异常处理方法独立出来,如:
C# codepublic class NestedExceptionHandling
{
public void MainMethod()
{
try
{
//some implementation
ChildMethod1();
}
catch(Exception exception)
{
//Handle exception
}
}private void ChildMethod1()
{
//some implementation
ChildMethod2();
}private void ChildMethod2()
{
//some implementation
}
}我想问的是:在三层架构中,是不是应该只有UI层才需要Try..Catch?
理由:因为DAL,BLL中的异常都可以通过UI层的调用捕捉到异常。
{
//Handle exception
throw;
}catch 后又throw就没必要catch了
并非如此吧,throw;是回避异常,但程序仍然继续执行。
如果是throw exception的话,就是主动抛出异常了。
不过感觉这样不太好!但习惯了