Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

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

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

A clear, brief summary is from the Python 2.5 what's new. In Javascript terms:

// XXX THIS EXAMPLE IS A SYNTAX ERROR
try {
  // Protected-block
} catch(e) {
  // Handler-block
} else {
  // Else-block
} finally {
  // Final-block
}

The code in Protected-block is executed. If the code throws an exception, Handler-block is executed; If no exception is thrown, Else-block is executed.

No matter what happened previously, Final-block is executed once the code block is complete and any thrown exceptions handled. Even if there’s an error in Handler-block or Else-block and a new exception is raised, the code in Final-block is still run.

Note that cutting Else-block and pasting at the end of Protected-block is wrong. If an error happens in Else-block, it must not be handled by Handler-block.

question from:https://stackoverflow.com/questions/4872170/javascript-try-catch-else-finally-like-python-java-ruby-etc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...