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 JavaScript Basics (Retired) Creating Reusable Code with Functions Random Number Challenge, Part II Solution

Chenghua Yang
Chenghua Yang
2,591 Points

How does `throw new Error` work?

Just saw throw new Error, a new argument to help detecting if the input was not a number or not.

But how does it work?

Can't we use alert() or document.write() to let users know what they sent was not a number?

Mark Casavantes
Mark Casavantes
Courses Plus Student 13,401 Points

Chenghua,

Yes, I think you can. See below.

''' <script type="text/javascript"> var num1 = 100; if(isNaN(num1)){ document.write(num1 + " is not a number <br/>"); }else{ document.write(num1 + " is a number <br/>"); } '''

Sorry, I could not help you on the throw new Error. Hopefully someone else can.

1 Answer

Jason Butler
Jason Butler
5,732 Points

Hi Chenghua,

The benefit of throwing a custom error is being able to control the flow of your program; note how when the instructor demonstrates it, the program stops once the error pops up. There are many instances when you would want the program to stop, rather than continue processing bad data.

With an alert box, the user is told of the error, then the code continues on to its end. They are great for testing code as you write it, but are hard to customize and don't look great, so finding other solutions for live programs is often preferred.

The try/catch keywords are also very useful for testing as well as for live pages. W3Schools has a quick rundown: http://www.w3schools.com/js/js_errors.asp It's a little confusing at first (it was for me anyway) but they can be pretty handy, especially for validating input.