Javascript try…catch…else…finally like Python, Java, Ruby, etc

后端 未结 5 853
别那么骄傲
别那么骄傲 2020-12-08 18:48

How can Javascript duplicate the four-part try-catch-else-finally execution model that other languages support?

A

5条回答
  •  时光取名叫无心
    2020-12-08 19:38

    Extending the idea of jhs a little, the whole concept could be put inside a function, to provide even more readability:

    var try_catch_else_finally = function(protected_code, handler_code, else_code, finally_code) {
      try {
        var success = true;
        try {
          protected_code();
        } catch(e) {
          success = false;
          handler_code({"exception_was": e});
        }
        if(success) {
          else_code();
        }
      } finally {
        finally_code();
      }
    };
    

    Then we can use it like this (very similar to the python way):

    try_catch_else_finally(function() {
      // protected block
    }, function() {
      // handler block
    }, function() {
      // else block
    }, function() {
      // final-block
    });
    

提交回复
热议问题