使用try / catch使得我无法在try / catch块之外使用变量

时间:2013-10-08 20:36:06

标签: c# try-catch scope

我有一个从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
}

3 个答案:

答案 0 :(得分:8)

只需在try / catch范围之外声明它。

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

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

答案 1 :(得分:1)

如果在提取产品时抛出了异常,那么您就没有产品可以采取行动。您似乎应确保只在未抛出异常时才执行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
}

答案 2 :(得分:0)

  

使这项工作的唯一方法是包含我的其他相关代码   在try / catch中?

没有。即使在webservice没有返回EntityDoesNotExist时抛出Product异常,您也需要在try块之外声明本地Product变量,以便在try之外的相关代码块可以访问它。

product

之外声明try{}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
}
相关问题