Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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