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
Ryan Scharfer
Courses Plus Student 12,537 PointsJS Errors : What is the advantage of throwing objects over throwing strings?
I am starting to learn about Javascript errors and how to throw exceptions. I haven't quite figured out why one should throw an object. Why wouldn't a string be sufficient?
Why is this preferred ......
function addTwoNumbers(a,b){
if (typeof a === "number" && typeof b ==="number")
return a+b;
else throw new Error("addTwoNumbers(): One or both of the arguments is not a number.");
}
over this?
function addTwoNumbers(a,b){
if (typeof a === "number" && typeof b ==="number")
return a+b;
else throw "addTwoNumbers(): One or both of the arguments is not a number.";
}
2 Answers
Colin Bell
29,679 PointsIn short, it helps immensely when debugging.
Here is a good write up explaining it: A String is not an Error
And another: The art of throwing JavaScript errors
Ryan Scharfer
Courses Plus Student 12,537 PointsThanks Colin. : )