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

Leonardo Motta
Leonardo Motta
11,284 Points

Is it the desired result of throw new Error?

Not sure if I got it right when we use the throw new Error, our program will stop no matter what? so the user won't be able to continue using it? is that really desired result? I would like to notice the user there was a problem with one of the value and then continue the program with the other values that are right

function getRandomNumber( lower, upper ) {
  if (lower < upper) {
    return Math.floor(Math.random() * (upper - lower + 1)) + lower;
  } else if (lower > upper) {
    var temp = lower;
    lower = upper;
    upper = temp;
    return Math.floor(Math.random() * (upper - lower + 1)) + lower;
  } else if (isNaN(lower) || isNaN(upper)) {
    throw new Error('One of the values is not a number');
  }   
}

console.log( getRandomNumber( 1, 'five' ) );
console.log( getRandomNumber( 1, 10 ) );
console.log( getRandomNumber( 30, 21 ) );

1 Answer

Steven Parker
Steven Parker
231,268 Points

Throwing the error to alert you of the problem allows you to fix the program so all output will be right.

But as you continue in the courses, you'll learn of a mechanism called try...catch that will allow you to respond to a "throw" but to also keep the program running. Click on the link if you'd like to dive into the documentation, or just keep plugging and you'll find out about it soon in the videos.

Leonardo Motta
Leonardo Motta
11,284 Points

Well, thank you for your answer, sometimes we just want to know that! dint know about this and that I would find more about this later, thanks