Last active
May 1, 2016 21:30
-
-
Save auchomage/70101975b5c08552a2a84a529838ba26 to your computer and use it in GitHub Desktop.
Questions regarding 'try-catch' blocks in node.js
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
/* | |
The example provided had a 'throw new Error' statement in the try section | |
see below | |
*/ | |
try { | |
throw new Error('Unable to do the thing you wanted'); | |
} catch(e){ | |
console.log(e.message); | |
} finally { | |
console.log('Finally block executed!'); | |
} | |
console.log('try-catch ended'); | |
/* | |
(2) With the challenge you set for us, you used a different format ie no | |
'throw new Error' statement occured in the 'try' block. Why not? | |
Below is my approach, which as you can see follows the format of the | |
example provided. | |
*/ | |
function doWork(){ | |
// throw an error that says unable to work | |
console.log("Unable to work!"); | |
} | |
try { | |
// call doWork() | |
throw new Error(doWork()); | |
} catch (e) { | |
console.log(e.message); | |
} finally { | |
console.log('Finally block executed!'); | |
} | |
console.log('try-catch2, ended.'); | |
/* Is this wrong? */ | |
/* (3) With the final challenge for the encrypted password program | |
You asked us to include 'try-catch' blocks. | |
Again in the solution, there was no 'throw new Error()' statement in the try blocks | |
ie, see below for an example | |
*/ | |
if (command === 'create') { | |
try { | |
var createdAccount = createAccount({ | |
name: argv.name, | |
username: argv.username, | |
password: argv.password | |
}, argv.masterPassword); | |
console.log('Account created!'); | |
console.log(createdAccount); | |
} catch (e) { | |
console.log('Unable to create the account!'); | |
} | |
/*A 'catch' block - somehow is able to catch any error from the 'try' block - that is missing a | |
'throw new Error()' statement. Since I was following the first example you gave us. I was wondering | |
'Why is he doing it like that?' | |
You did the same thing for the 2nd 'try-catch' block. | |
Finally, I see that the 'try-catch' blocks are nested within the conditional (if) statement. Is this the general rule to | |
be followed when deploying 'try-catch' blocks? | |
*/ | |
} else if (command === 'get') { | |
try{ | |
var fetchedAccount = getAccount(argv.name, argv.masterPassword); | |
if (typeof fetchedAccount === 'undefined') { | |
console.log('Account not found'); | |
} else { | |
console.log('Account found!'); | |
console.log(fetchedAccount); | |
} | |
} catch (e) { | |
console.log('Unable to get the requested account.'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment