代码之家  ›  专栏  ›  技术社区  ›  JimDel

如何在C中发生异常后从一系列单独的语句中分离出来#

  •  1
  • JimDel  · 技术社区  · 16 年前

    我有一个执行一组文件复制操作的按钮单击事件。每个复制操作都包含在自己的try/catch中。我希望在用户取消或出错的情况下,它退出文件复制操作的其余部分,并将用户返回主程序。因为每个文件复制语句都依赖于特定的条件,所以我不能只用一个try/catch来包围它们。有办法吗?

    谢谢

    5 回复  |  直到 16 年前
        1
  •  1
  •   Johnno Nolan    16 年前

    你可以放一个 return 在捕捉中

    例如

    public void BigMethod()
    {
        try
        { 
           // op1
        } catch
        {
          //some cleanup
          //some error message
          return // this will exit method here
        }
    
        try
        { 
           // op2
        } catch
        {
          //some cleanup
          //some error message
          return // this will exit method here
        }
    
    }
    
        2
  •  2
  •   BeemerGuy    16 年前

    一种方法:
    把所有的试捕放在一个大的试捕中。
    如果其中一个失败了,抛出一个异常,以便它被外部try catch捕获,这样其他try catch就不会执行。

    例子:

    try
    {
        try
        {
            if(UserWantsTo())
                CopyFile();
            else
                throw new Exception("User doesn't want Copy1");
        }
        catch(Exception Copy1Ex)
        {
            throw Copy1Ex;
        }
    
        // repeat as many file-copies here.
    
    }
    catch (Exception OuterException)
    {
        MessageBox.Show("One of the file copy operations failed: " + OuterException.ToString());
    }
    
        3
  •  2
  •   roman m    16 年前
    bool problem = false;
    
    try{}
    catch(Exception ex)
    {
    //do your thing 
    problem = true;
    }
    
    if(!problem){try/catch}
    
        4
  •  1
  •   Gabe    16 年前

    允许用户取消:

    由于在主UI线程上处理文件副本,因此需要为此操作创建一个线程。使用线程设置后,UI将能够监听取消事件,您可以选择不执行文件复制。

    如果有错误,请跳过:

    刚刚准备好 error 到 true 如果发生异常:

    // Process file 1
    if(!ProcessFile()){
    
       // Processfile 2
       if(!ProcessFile()){
    
         //etc..
       }
    
    }
    
    
    private bool ProcessFile(){
        bool error = false;
    
        try{
           // do work   
        }
        catch{
           error = true;    
        }
        return error;
    }
    
        5
  •  1
  •   Henk Holterman    16 年前

    有办法吗?

    对。不要用一个try/catch包围每个人。如果确定需要所有这些catch块(日志记录),则从catch块重新抛出异常。

    try
    {
        CopyAction();
    }
    catch (Exception ex)
    {
       LogError(ex);
    
       throw; // not: throw ex;       
       // or maybe:
       throw new MoreSpecificException("message", ex); 
    }
    

    如果有疑问,请张贴一些(简化)代码以供进一步讨论。