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

后端 未结 5 860
别那么骄傲
别那么骄傲 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:30

    Javascript does not have the syntax to support the no-exception scenario. The best workaround is nested try statements, similar to the "legacy" technique from PEP 341

    // A pretty-good try/catch/else/finally implementation.
    try {
      var success = true;
      try {
        protected_code();
      } catch(e) {
        success = false;
        handler_code({"exception_was": e});
      }
      if(success) {
        else_code();
      }
    } finally {
      this_always_runs();
    }
    

    Besides readability, the only problem is the success variable. If protected_code sets window.success = false, this will not work. A less readable but safer way uses a function namespace:

    // A try/catch/else/finally implementation without changing variable bindings.
    try {
      (function() {
        var success = true;
        try {
          protected_code();
        } catch(e) {
          success = false;
          handler_code({"exception_was": e});
        }
        if(success) {
          else_code();
        }
      })();
    } finally {
      this_always_runs();
    }
    

提交回复
热议问题