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

gary peart
gary peart
6,496 Points

Does "throw new Error" terminate a function in the same way as the 'return' does?

Does the "throw new Error('error message goes here')" terminate a function in the same way as the 'return' does?

I've got the following to work fine without the 'throw new Error' line included, but when I include it the code it does not work complete the third console.log after the prompt....


function getRandomNumber( lower, upper ) {

    if (isNaN(lower) || isNaN(upper) ) {

      if (isNaN(lower)) {
            lower = prompt('Please provide a new low number');
            lower = parseInt(lower);
            }else if(isNaN(upper)){
            upper = prompt('Please provide a new upper number');
            upper = parseInt(upper);
      }
            throw new Error('One of the entries is not a number!!!');     

     }
    return Math.floor(Math.random() * (upper - lower + 1)) + lower;
}
console.log( getRandomNumber( 5 , 24 ) );
console.log( getRandomNumber( 1, 100 ) );
console.log( getRandomNumber( 200, 'five hundred' ) );
console.log( getRandomNumber( 1000, 20000 ) );
console.log( getRandomNumber( 50, 100 ) );

Please, what have I done wrong?

Thanks in advance!

Gary

2 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi Gary,

When throwing a manual error within a function for example, we are telling the JavaScript compiler to cease code execution from where it's declared which then prevents any code following it from being executed in the same context. Unlike the return statement; throw terminates all code in the existing context which means that all code declared after your declaration would also be stopped.

It is best to use the Error function only when you think a critical problem has occurred, for simple things such as number processing it's fine just to use return as the user will never think to look for a code execution problem in the developer console in their browser.

Hope that helps.

gary peart
gary peart
6,496 Points

I understand 'throw' and 'Error' more clearly now. Many thanks Chris!