2013-04-08 70 views
0

嗨,我有以下方法。對象引用異常終止塊

public bool IsTableExist(string tableName) 
    { 
     try 
     { 

      if (Utility.Utility.CreatedTable.Contains(tableName.ToLower())) 
       return true; 
      else 
      { 
       _dataAccess.openconnection(); 
       if (!_dataAccess.isTableExist(tableName)) 
        return false; 
       Utility.Utility.CreatedTable.Add(tableName.ToLower()); 
       return true; 
      } 
     } 
     catch (Exception ex) 
     { 
      Logger.WriteLogFile("QueryBuilder", "IsTableExist", ex.StackTrace); 
     } 
     finally 
     { 
      _dataAccess.closeconnection(); 
     } 
     return false; 
    } 

這裏我得到fllowing例外:

Object reference not set to an instance of an object. 
at DataAccessLayer.DataAccess.closeconnection() 
at QueryBuilder.QueryBuilder.IsTableExist(String tableName) 
at ObjectFilling.BusinessLogic.GetDataTypeForAllTags(DataTable tagDetails) 

如何解決exception.I有OpenConnection的()和closeconnection(),它被用於與database.The通信異常拋出方法在調用closeconnection()方法時終止塊,但未調用openconnection().openconnectio()僅在代碼到達else塊時調用。我可以在else塊中使用bool變量來通知finally塊何時調用closeconnection.Or有沒有其他方法可以修改代碼,以便不會發生異常。 請在這方面幫助我。

回答

0
bool isOpen = false; 
try 
{ 
    _dataAccess.openconnection(); 
    isOpen = true; 
} 
finally 
{ 
    if (isOpen) 
    _dataAccess.closeconnection(); 
} 

我發現這是工作的解決方案。任何進一步的想法都會受到歡迎。在這種情況下,連接打開時會設置bool變量。