Created
May 1, 2016 02:32
-
-
Save jlongster/a3aadef1d05f2528fbc63fb171e7d399 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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