簡體   English   中英

使用try / catch可以做到這一點,所以我不能在try / catch塊之外使用變量

[英]Using try/catch makes it so I can't use the variable outside of the try/catch block

我有一個從Web服務獲取Product對象的代碼。 如果沒有產品,則返回EntityDoesNotExist異常。 我需要處理這個問題。但是,我還有很多其他代碼用於處理返回的Product ,但是如果此代碼不在try / catch內,則它將無法正常工作,因為Product基本上沒有定義。 是使這項工作包含在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
}

只需在try / catch范圍之外聲明它即可。

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

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

如果在獲取您的產品時拋出異常,那么您就沒有可操作的產品。 看來您應該確保僅在不引發異常的情況下才執行UI代碼。 這可以通過移動內部的代碼來完成try塊:

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

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

是使這項工作包含在try / catch中的其他相關代碼的唯一方法嗎?

EntityDoesNotExist 。即使Web服務未返回Product ,即使拋出EntityDoesNotExist異常,您也需要在try塊之外聲明本地Product變量,以便try塊之外的相關代碼可以訪問它。

try{}catch{}之外聲明product

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM