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
brandonlind2
7,823 PointsCan someone explain to me what a throw, catch and try is and if it's necessary to learn in JavaScript?
I saw throws, catches and try on MDN. I'm wondering what they are.
2 Answers
Ken Alger
Treehouse TeacherBrandon;
They are something you will definitely need in Node.js but are, in my opinion, fairly easy to pick up. They get used quite a bit for I/O operations with the file system, database, API calls, etc. So for example you would do something like:
try {
// Try to do something here, connect to a database, write a file,
// do something with input checking, etc.
}
catch(error) {
// Do something with the error such as:
console.log(error);
}
finally {
// Do something in here regardless of the results of the try... catch events
}
Post back with other questions.
Happy coding,
Ken
Roy Penrod
19,810 PointsThey're programming constructs for handling errors.
A "try" statement lets you try to execute a piece of code. If an error (often called an "exception" in programming) occurs, the exception is "thrown". A "catch" statement lets you look for the exceptions and handle them within your code.
You can also throw your own exceptions when something unexpected happens.
And yes, you will need to learn them at some point.
brandonlind2
7,823 PointsWould I need to know them before a junior or an intermediate JavaScript job or could this be something l could learn when tackling node.js?
brandonlind2
7,823 Pointsbrandonlind2
7,823 PointsThanks man! I'm trying to wrap my head around everything I left to learn for an entry job. Would this have alot of front end value?
Ken Alger
Treehouse TeacherKen Alger
Treehouse TeacherBrandon;
Yes, you will encounter them for front end cases as well. For example, if you have an input field that wants a number to which you will be multiplying by, say 3. That's great until someone inputs a string "foo" into your input field, so inside a
tryblock you can do some data validation, for example. Or on the front end if you need to make a call to an API, you may want to try to see if the connection is in place before doing something to avoid, or catch, errors.Hope it helps,
Ken
brandonlind2
7,823 Pointsbrandonlind2
7,823 PointsYeah man that helps thanks!