简体   繁体   English

使用try / catch可以做到这一点,所以我不能在try / catch块之外使用变量

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

I have a code that gets a Product object from a web service. 我有一个从Web服务获取Product对象的代码。 If there is no product, it returns an EntityDoesNotExist exception. 如果没有产品,则返回EntityDoesNotExist异常。 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. 我需要处理这个问题。但是,我还有很多其他代码用于处理返回的Product ,但是如果此代码不在try / catch内,则它将无法正常工作,因为Product基本上没有定义。 Is the only way to make this work to include my other related code within the try/catch? 是使这项工作包含在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
}

Just declare it outside the try/catch scope. 只需在try / catch范围之外声明它即可。

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

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

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. 看来您应该确保仅在不引发异常的情况下才执行UI代码。 That can be done by moving that code inside the try block: 这可以通过移动内部的代码来完成try块:

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

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

Is the only way to make this work to include my other related code within the try/catch? 是使这项工作包含在try / catch中的其他相关代码的唯一方法吗?

No. Even though an EntityDoesNotExist exception is thrown if the webservice does not return a Product , you need to declare your local Product variable outside of the try block so that your related code outside of the try block can access it. EntityDoesNotExist 。即使Web服务未返回Product ,即使抛出EntityDoesNotExist异常,您也需要在try块之外声明本地Product变量,以便try块之外的相关代码可以访问它。

Declare product outside of the try{}catch{} : 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