Skip to main content
 首页 » 编程设计

c#之如果 bool 值为假或我的条件不返回任何值,如何调用 Catch

2024年02月23日15cmt

我只是想知道如何解决我的情况,这是我的代码

 try 
            { 
                bool b; 
                foreach (string file in files) 
                { 
 
                    #region donloadfiles 
                    if (b = file.Contains(story)) 
                    { 
                        try 
                        { 
                            logger.Info("calling xml creation Method"); 
                            baseMeta(story, XML); 
                            logger.Info("XML created"); 
                        } 
                        catch (Exception ex) 
                        { logger.Error(ex.Message); throw; } 
 
                        logger.Info("calling Download Method"); 
                        Download(file, story, xml, program); 
                        logger.Info("Download Method processed successfully"); 
                    } 
                    #endregion 
                } 
 
 
            } 
 
            catch (Exception ex) 
            { logger.Error(ex.Message); throw; } 

正如 promise 的那样,这是我的主要方法,包含 try catch block

 try 
            { 
 
                //update the status here in DB 
               Status = "Closed"; 
               Update(status); 
            } 
 
            catch (Exception ex) 
            { 
 
                Status = "Failed"; 
                Update(status); 
                break; 
            } 

我有目录“for eg:C:\”,我的 getlist 方法获取所有记录并将其传递到我的 foreach 循环“foreach(文件中的字符串文件)”然后我有一个条件

如果 (b = file.Contains(story)) 检查我的任何文件的名称为“story”,然后在里面做一些逻辑。这个东西很好用。

现在我要做的是,如果没有匹配的文件,那么我必须强制调用 catch 并抛出到主 catch,我正在对我的主 catch 进行一些逻辑更新。

有人请告诉我如何解决这种情况。

提前致谢

请您参考如下方法:

what am trying to do is,if none of the files are matching then i have to forcefully call the catch and throw to the main catch,am doing some logic update in my main catch.

bool anyMatch = false; 
 
foreach (.....) 
{ 
      if (b = file.Contains(story)) 
         anyMatch = true; 
} 
 
if(!anyMatch) 
    throw ... //this will be caught by main catch 

在 foreach 循环之外保留一个 bool 变量。如果有任何文件匹配,则将其设置为 true。如果在 foreach 循环结束时为 false 则抛出异常