Debug.Assert vs Exception Throwing

前端 未结 8 1386
囚心锁ツ
囚心锁ツ 2020-12-12 10:49

I\'ve read plenty of articles (and a couple of other similar questions that were posted on StackOverflow) about how and when to use assertions, and I understood the

8条回答
  •  爱一瞬间的悲伤
    2020-12-12 11:36

    I think a (contrived) practical example may help illuminate the difference:

    (adapted from MoreLinq's Batch extension)

    // 'public facing' method
    public int DoSomething(List stuff, object doohickey, int limit) {
    
        // validate user input and report problems externally with exceptions
    
        if(stuff == null) throw new ArgumentNullException("stuff");
        if(doohickey == null) throw new ArgumentNullException("doohickey");
        if(limit <= 0) throw new ArgumentOutOfRangeException("limit", limit, "Should be > 0");
    
        return DoSomethingImpl(stuff, doohickey, limit);
    }
    
    // 'developer only' method
    private static int DoSomethingImpl(List stuff, object doohickey, int limit) {
    
        // validate input that should only come from other programming methods
        // which we have control over (e.g. we already validated user input in
        // the calling method above), so anything using this method shouldn't
        // need to report problems externally, and compilation mode can remove
        // this "unnecessary" check from production
    
        Debug.Assert(stuff != null);
        Debug.Assert(doohickey != null);
        Debug.Assert(limit > 0);
    
        /* now do the actual work... */
    }
    

    So as Eric Lippert et al have said, you only assert stuff that you expect to be correct, just in case you (the developer) accidentally used it wrong somewhere else, so you can fix your code. You basically throw exceptions when you have no control over or cannot anticipate what comes in, e.g. for user input, so that whatever gave it bad data can respond appropriately (e.g. the user).

提交回复
热议问题