Do you consider this technique “BAD”?

前端 未结 28 1511
借酒劲吻你
借酒劲吻你 2021-02-02 10:57

Sometimes you need to skip execution of part of a method under certain non-critical error conditions. You can use exceptions for that, but exceptions generally are not

28条回答
  •  灰色年华
    2021-02-02 11:32

    Basically you just described goto. I use goto in C all the time. I don't consider it bad, unless you use it to emulate a loop (never ever do that!). My typical usage of goto in C is to emulate exceptions (C has no exceptions):

    // Code
    
    if (bad_thing_happened) goto catch;
    
    // More code
    
    if (bad_thing_happened) goto catch;
    
    // Even more code
    
    finally:
    
    // This code is executed in any case
    // whether we have an exception or not,
    // just like finally statement in other
    // languages
    
    return whatever;
    
    catch:
    
    // Code to handle bad error condition
    
    // Make sure code tagged for finally
    // is executed in any case
    goto finally;
    

    Except for the fact that catch and finally have opposite order, I fail to see why this code should be BAD just because it uses goto, if a real try/catch/finally code works exactly like this and just doesn't use goto. That makes no sense. And thus I fail to see why your code should be tagged as BAD.

提交回复
热议问题