object m_myObject = null;
try{
m_myObject = SomeFunction(ref m_somePar);
}catch(Exception ex){
//Some code;
}
然而,这样问题就来了,当调用SomeFunction出现异常后,SomeFunction中的m_tempObject对象根本没有机会调用Dispose来释放资源。
于是修改代码为:
模块A中的函数:
public object SomeFunction(ref object i_someParameter){
SomeObject m_tempObject = new SomeObject(); //m_tempObect need release after use it.
object m_result = null;
try{
//Some code with SomeObject m_tempObject;
}catch(Exception ex){
m_result = null;
//some code
}
finally{
m_tempObject.Dispose();
}
return m_result;
}
模块B中的调用:
object m_myObject = SomeFunction(ref m_somePar);
if(m_myObject ==null){
//some code
}else{
//some code
}
然而这样还是有问题,就是你不知道调用模块A中的函数时,当返回null后,A中到底出现了什么问题。
也就是说,这里我想让B模块来Catch异常,而不想让A模块来处理。
简单的办法是在A模块的函数中catch到异常后,重新再抛出一个新异常:
public object SomeFunction(ref object i_someParameter){
SomeObject m_tempObject = new SomeObject(); //m_tempObect need release after use it.
object m_result = null;
try{
//Some code with SomeObject m_tempObject;
}catch(Exception ex){
m_result = null;
//some code
throw new Exception("Some message");
}
finally{
m_tempObject.Dispose();
}
return m_result;
}
这样B模块中可以知道A中发生了什么事情,从而进一步处理。然而这样的问题是:
系统性能下降和异常类的改变。当然,假如直接抛出原来的异常也行,但那样没有必要,后来这样改代码:
模块A的函数:
public object SomeFunction(ref object i_someParameter){
using(SomeObject m_tempObject = new SomeObject()){
object m_result = null;
//some code with m_tempObject;
return m_result;
}
}
//模块B的调用:
object m_myObject = null;
try{
m_myObject = SomeFunction(ref m_somePar);
}catch(Exception ex){
//Some code;
}
虽然B中还是用到了try-catch结构,但意义是不一样的。假如A是不可知模块,例如你是A模块提供方,那么这样的方法给你的用户提供了很好的灵活性。
假如你是A模块的使用方,那么你完全可以自己控制try-catch结构。
好了,先就这一点点心得。有时间再写一些。
http://www.cnblogs.com/WuCountry/archive/2006/11/24/570719.html
评论加载中…
![]() |