Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Suck on Use a try block in the appropriate place to catch an error. Include a catch block with error as the parameter.

I am on the node.js basics tutorial. Objective test = "Using try and catch"

It starts off as this:

Question: Something bad is going to happen. Use a try block in the appropriate place to catch an error. Include a catch block with error as the parameter.

Code: var jsonString = 'This is not a JSON String'; var jsonObject = JSON.parse(jsonString);

What I added (complete) but still failing: var jsonString = 'This is not a JSON String'; var jsonObject = JSON.parse(jsonString);

try { jsonObject; } catch (error) {

};

Any thoughts here?

8 Answers

Bil Benhamou
Bil Benhamou
6,022 Points

The variables have to be in the Try block! The block is gonna try to parse jsonString as a JSON string which is not.

try {
 var jsonString = 'This is not a JSON String';
var jsonObject = JSON.parse(jsonString);

} catch (error) {

}

Bil is right on with this answer. I added a console.log(error) to the catch and it passed. Take that as you will.

try { var jsonString = 'This is not a JSON String'; var jsonObject = JSON.parse(jsonString);

} catch (error) {

}

Remove the semicolon at the end of the catch block

That did not work.

Oh here is better syntax of what I am doing

var jsonString = 'This is not a JSON String';
var jsonObject = JSON.parse(jsonString);

try {
  jsonObject
} catch (error) {

}
var jsonString = 'This is not a JSON String';
var jsonObject = JSON.parse(jsonString);

try {
  jsonObject
} catch (error) {

}

var jsonString = 'This is not a JSON String'; try { var jsonObject = JSON.parse(jsonString); } catch(error) {

}

This passed for me

try { var jsonObject = JSON.parse(jsonString); }catch(error){ var jsonString = 'This is not a JSON String'; }

const jsonString = 'This is not a JSON String'; const jsonObject = JSON.parse(jsonString);

try { const jsonObject = JSON.parse(jsonString); }catch(error){ const jsonString = 'This is not a JSON String'; }