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 Handling Parsing and Status Code Errors

James Kim
James Kim
8,475 Points

Why do you need Try and Catch method?

So i have this code on the bottom with Try and Catch method to parse data into JSON format....

if(response.statusCode === 200){
    try {
        var profile = JSON.parse(body)
        printMessage(username, profile.badges.length, profile.points.JavaScript);
     catch(error){
        printError(error);
    }
}else{
    printError({
        message: "There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ") "
    });
}

but I don't understand why there's a try and catch for the parse error when the code works perfectly fine without the try and catch. Code on bottom....

if(response.statusCode === 200){
    var profile = JSON.parse(body)
    printMessage(username, profile.badges.length, profile.points.JavaScript);

}else{
    printError({
        message: "There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode]                
+ ") "
    });
}

So why is the Try and Catch necessary?

Thank you in advance.

  • James

2 Answers

Kevin Korte
Kevin Korte
28,149 Points

Because without the catch, you can still have a response status code of 200, but the parse fails, and now your program has no way of recovering from it, so it's just going to error out, and possibly display error information to your user, you don't want them to have.

It only works, as you mentioned, when it works, but there is a chance it won't work, now what? So we try something, and if it errors, we catch the error, and do something with it.

If the status code isn't 200, we don't even bother trying to parse the json.

Jeff Lemay
Jeff Lemay
14,268 Points

That second block of code works fine without the try/catch in your perfect dev environment. But you can't test for all types of errors for all types of users in all types of environments. You add a try/catch block because you never want to have an error be uncaught, think of it like "just in case everything goes haywire".