2013-10-08 54 views
0

我有一個代碼從web服務獲取Product對象。如果沒有產品,則返回EntityDoesNotExist異常。我需要處理這個..但是,我有很多其他代碼處理返回Product,但如果此代碼不在try/catch中,它不起作用,因爲Product基本上未定義。是否只有這樣做才能在try/catch中包含我的其他相關代碼?這似乎很sl。。使用try/catch使得我不能使用try/catch塊外的變量

代碼示例:

try { 
    Product product = catalogContext.GetProduct("CatalogName", "ProductId"); 

} catch(EntityDoesNotExist e) { 
    // Do something here 
} 

if(dataGridView1.InvokeRequired) { 
    // Do something in another thread with product 
} 
+2

你如何訪問'product'外的try-catch的_declared_ ** **在它:這可以通過移動代碼try塊做什麼? –

回答

8

就宣佈它的try/catch範圍之外。

Product product; 
try 
{ 
    product = catalogContext.GetProduct("CatalogName", "ProductId"); 
} 
catch (EntityDoesNotExist e) 
{ 
    product = null; 
} 

if (dataGridView1.InvokeRequired) 
{ 
    // use product here 
} 
+1

使用這個,之後我嘗試做'MessageBox.Show(p.SomeProperty)',它說:使用未賦值的局部變量'p' – sk099

+2

@StephenKnoth您必須在'try'前面賦值'product'的某個值。 'Product product = null;'),或者在catch中(正如這個解決方案所做的那樣),或者讓'catch'再次拋出'throw',而不是*只將它分配給'try'。 'try'中的東西被認爲是可以運行的,並不像它們將運行,所以'p'可能在該上下文中未被分配。 –

+0

@TimS。是的,就是這樣。謝謝。 – sk099

1

是使這項工作,包括我的其他相關代碼的try/catch內 的唯一途徑?

號即使如果Web服務沒有返回ProductEntityDoesNotExist拋出異常,您需要聲明try塊的本地Product變量外,這樣try塊之外的相關的代碼可以訪問它。

聲明producttry{}catch{}之外:

Product product = null; 

try 
{   
    product = catalogContext.GetProduct("CatalogName", "ProductId");  
} 
catch(EntityDoesNotExist e) 
{ 
    // Do something here 
} 

if(dataGridView1.InvokeRequired) 
{ 
    // Do something in another thread with product 
} 
0

如果在提取產品時引發異常,那麼您沒有產品可以採取行動。如果你沒有拋出異常,你應該確保你只執行UI代碼。如果它是

try 
{ 
    Product product = catalogContext.GetProduct("CatalogName", "ProductId"); 

    if (dataGridView1.InvokeRequired) 
    { 
     // Do something in another thread with product 
    } 
} 
catch (EntityDoesNotExist e) 
{ 
    // Do something here 
}