1

I have a code that gets a Product object from a web service. If there is no product, it returns an EntityDoesNotExist exception. I need to handle this.. However, I have a lot of other code that deals with the returned Product, but if this code is not within the try/catch, it doesn't work because Product is basically not defined. Is the only way to make this work to include my other related code within the try/catch? This seems really sloppy.

Code example:

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

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

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

3 回答 3

10

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

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

if (dataGridView1.InvokeRequired)
{
    // use product here
}
于 2013-10-08T20:38:26.857 回答
2

If an exception was thrown when fetching your product then you don't have a product to act on. It seems that you should be ensuring that you only execute the UI code if you didn't throw an exception. That can be done by moving that code inside the try block:

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

    if (dataGridView1.InvokeRequired)
    {
        // Do something in another thread with product
    }
}
catch (EntityDoesNotExist e)
{
    // Do something here
}
于 2013-10-08T20:47:04.520 回答
0

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

不可以。即使EntityDoesNotExistweb 服务不返回 a 时会引发异常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
}
于 2013-10-08T20:38:01.240 回答