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 Node.js Basics (2014) Building a Command Line Application Using try and catch

Vladyslav Burdeniuk
Vladyslav Burdeniuk
16,795 Points

Where should I place try-catch block of code

Where should I place try-catch block of code

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

Hi Vladyslav,

The following worked for me:

var jsonString = 'This is not a JSON String';

try {

  var jsonObject = JSON.parse(jsonString);

} catch(error){

  console.log(error);

}

As you can see, the potentially risky statement parsing the string into JSON is put within a try block, with a catch block following to handle any error.

In a real application, if the string value is only known at run-time, I guess that assignment could be moved into the try block as well. Can anyone else chime in on that? Both versions pass the code challenge.

Hope this helps,

Ajay

1 Answer

Vladyslav Burdeniuk
Vladyslav Burdeniuk
16,795 Points

Ajay, thank you) I have solved that issue by putting assignment in the try block as well