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

Chetan Jaisinghani
Chetan Jaisinghani
2,896 Points

Calling the function after it throws an error

So we throw out an error when either of the arguments passed is not a number. My question is, if we are calling the function multiple times i.e. sometimes with correct arguments and sometimes with incorrect arguments, why does the function just stop after it executes the first time? What happens to console.log statements that pass correct arguments?

2 Answers

From my understanding Javascript is designed in the way like most programming language are, that when it encounters and error it will just stop.

In that example you are specifically telling it to "Error" using the Error(); function not just print out a string that says "Error".

throw new Error('Both arguments must be numbers');

Because you are telling it that it has errored it has in turn stopped processing any further code.

If you wanted it to continue on, you would just have it print out the string 'Both arguments must be numbers' and not error using the Error(); function.

console.log('Both arguments must be numbers');

It would then continue on with all the other numbers that are in fact numbers while printing out the string when it encounters one that isn't.

More info on the error function:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

Chetan Jaisinghani
Chetan Jaisinghani
2,896 Points

Thank you so much for explaining that!