使用 try/catch 就可以让我不能在 try/catch 块之外使用变量

本文关键字:catch try 变量 不能 就可以 使用 | 更新日期: 2023-09-27 18:34:24

我有一个从 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 就可以让我不能在 try/catch 块之外使用变量

只需在 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
}

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

不。即使 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
}