Skip to content

Instantly share code, notes, and snippets.

@jlongster
Created May 1, 2016 02:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlongster/a3aadef1d05f2528fbc63fb171e7d399 to your computer and use it in GitHub Desktop.
Save jlongster/a3aadef1d05f2528fbc63fb171e7d399 to your computer and use it in GitHub Desktop.
// Example code, see try/catch/throw implementation below
function bar(x) {
if(x < 0) {
Throw(new Error("error!"));
}
return x * 2;
}
function foo(x) {
return bar(x);
}
function main() {
Try(
function() {
console.log(foo(1));
console.log(foo(-1));
},
function(ex) {
console.log("caught", ex);
}
);
}
main();
// Output:
// 2
// caught [Error: error!]
// try/catch/throw implementation
var tryStack = [];
function Try(body, handler) {
var ret;
var exc = callCC(function(cont) {
tryStack.push(cont);
ret = body();
});
tryStack.pop();
if(exc) {
return handler(exc);
}
return ret;
}
function Throw(exc) {
if(tryStack.length > 0) {
tryStack[tryStack.length - 1](exc);
}
console.log("unhandled exception", exc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment