Created
September 14, 2017 08:23
-
-
Save WillsB3/eed90e26f54f3a52cbf9a5d4f564641b to your computer and use it in GitHub Desktop.
Custom exception creation and usage in JavaScript
This file contains hidden or 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
// From http://eloquentjavascript.net/08_error.html | |
// Error definition | |
function InputError(message) { | |
this.message = message; | |
this.stack = (new Error()).stack; | |
} | |
InputError.prototype = Object.create(Error.prototype); | |
InputError.prototype.name = "InputError"; | |
// Code throwing this type of exception | |
function promptDirection(question) { | |
var result = prompt(question, ""); | |
if (result.toLowerCase() == "left") return "L"; | |
if (result.toLowerCase() == "right") return "R"; | |
throw new InputError("Invalid direction: " + result); | |
} | |
// Handling | |
for (;;) { | |
try { | |
var dir = promptDirection("Where?"); | |
console.log("You chose ", dir); | |
break; | |
} catch (e) { | |
if (e instanceof InputError) | |
console.log("Not a valid direction. Try again."); | |
else | |
throw e; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment