代码之家  ›  专栏  ›  技术社区  ›  Eric Ness

注释try-catch语句

  •  4
  • Eric Ness  · 技术社区  · 17 年前

    // Possible comment location 1
    try
    {   
        // real code
    }
    // Possible comment location 2
    catch
    {
        // Possible comment location 3
    
        // Error handling code
    
    }
    
    8 回复  |  直到 17 年前
        1
  •  17
  •   Bill the Lizard    17 年前

    我通常做以下几件事。如果只有一个异常被处理,我通常不会麻烦,因为它应该是自文档化的。

    try
    {   
        real code // throws SomeException
        real code // throws SomeOtherException
    }
    catch(SomeException se)
    {
        // explain your error handling choice if it's not obvious
    }
    catch(SomeOtherException soe)
    {
        // explain your error handling choice if it's not obvious
    }
    
        2
  •  10
  •   Jay Bazuzi Buck Hodges    17 年前

    “评论是谎言”

        3
  •  5
  •   Jason Jackson    17 年前

    我认为这根本不重要。

    为什么? 代码就是这样,不是这样 什么 首先,代码正在运行。这并不是说你不应该用简洁的评论来解释复杂的逻辑,而是为什么更重要。

        4
  •  4
  •   glenatron    17 年前

    try
    { 
       performDifficultAct( parameter );
    }
    catch (ArgumentOutOfRangeException couldNotFindArgument)
    {
       // handle exception
    }
    catch (Exception otherUnknownException )
    {
       // handle exception
    }
    

    编辑:为了澄清一点,这里有一点关于我如何使用这些“catch”语句为维护程序员和用户/支持/质量保证/使用软件的任何其他人提供有用的信息。这也是我绝对希望在代码中添加额外注释的情况的说明:

    public void PerformSomeActionOrOther(string parameter)
    {
      try
      { 
         // For some reason an eleven character string causes a bluescreen from Kernel32
         if (parameter.Length==11) parameter+=" ";
    
         performDifficultAct( parameter );
      }
      catch (ArgumentOutOfRangeException couldNotFindArgument)
      {
         this.Log.WriteLn("Argument out of range exception in ArbitraryClass.PerformSomeActionOrOther");
         this.Log.WriteLn(String.Format("Probable cause is that {0} is not in the array", parameter));
         this.Log.WriteLn(String.Format("Exception: {0}", couldNotFindArgument.Message));
      }
      catch (Exception otherUnknownException )
      {
         this.Log.WriteLn("Unexpected exception in ArbitraryClass.PerformSomeActionOrOther");
         this.Log.WriteLn(String.Format("Exception: {0}", otherUnknownException.Message));
         throw( otherUnknownException );
      }
    }
    
        5
  •  2
  •   Charlie Martin    17 年前

    绝对不要评论它的顶部,因为除了“在这里启动异常处理块”之外,你还能说些什么呢?对catch语句的评论更好,但总的来说,你会怎么说?“处理NullPointerException”?

        6
  •  1
  •   Sarat    17 年前

    我认为写得好的try/catch应该简洁具体。我同意@Jason的观点,即 为什么? 更重要的是,同样重要的是,保持catch中的代码尽可能简洁。

    如果您使用特定的异常进行捕获,这也会有所帮助。例如,如果您使用的是Java,请尝试捕获NullPointerException,而不是泛型异常。这应该解释为什么存在try-catch,以及您正在做什么来解决它。

        7
  •  1
  •   Elie    17 年前

    //comment 1: code does XYZ, can cause exceptions A, B, C
    try {
        //do something
    }
    //comment 2: exception A occurs when foo != bar
    catch (ExceptionA a) {
        //do something
    }
    //comment 3: exception B occurs when bar is null
    catch (ExceptionB b) {
        //do something
    }
    //comment 4: exception B occurs when foo is null
    catch (ExceptionC c) {
        //do something
    }
    
        8
  •  0
  •   Michael Meadows    17 年前

    我知道这不是你想要的答案,但请不要发表评论。如果您的代码不够清晰,无法独立运行而不进行注释,那么您应该重构它,直到它变得清晰为止。 Jeffrey Palerm o刚刚写了一篇文章 blog post

    通常,注释倾向于记录以下内容之一:

    • 代码太紧凑了。看起来像这样的东西: ++i?--g:h-i;
    • 可一次性使用或没有明确理由存在的代码

    bool retries = 0;
    while (retries < MAX_RETRIES)
    {
        try
        {
            ... database access code
            break;
        }
        // If under max retries, log and increment, otherwise rethrow
        catch (SqlException e)
        {
            logger.LogWarning(e);
            if (++retries >= MAX_RETRIES)
            {
                throw new MaxRetriesException(MAX_RETRIES, e);
            }
        }
        // Can't retry.  Log error and rethrow.
        catch (ApplicationException e)
        {
            logger.LogError(e);
            throw;
        }
    }
    

    虽然上面的注释促进了可重用性,但实际上您必须同时维护代码和注释。可以(而且更可取)重构它,以便在没有注释的情况下更加清晰。

    bool retries = 0;
    while (canRetry(retries))
    {
        try
        {
            ... database access code
            break;
        }
        catch (SqlException e)
        {
            logger.LogWarning(e);
            retries = incrementRetriesOrThrowIfMaxReached(retries, e);
        }
        catch (ApplicationException e)
        {
            logger.LogError(e);
            throw;
        }
    }
    
    ...
    
    private void incrementRetriesOrThrowIfMaxReached(int retries, Exception e)
    {
        if (++retries >= MAX_RETRIES)
            throw new MaxRetriesException(MAX_RETRIES, e);
    
        return retries;
    }
    
    private bool canRetry(int retries)
    {
        return retries < MAX_RETRIES;
    }
    

    推荐文章