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

Hoessein Abd
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Hoessein Abd
Python Web Development Techdegree Graduate 19,107 Points

Why does the 'Throw new error' function end the program?

function getRandomNumber( lower, upper ) {
  if (isNaN(lower) || isNaN(upper) ) {
    throw new Error('You can only enter numbers');
  }
  return Math.floor(Math.random() * (upper - lower + 1)) + lower; 
}

document.write( getRandomNumber( 'nine', 24 ) );
document.write( getRandomNumber( 1, 100 ) );
document.write( getRandomNumber( 200, 'five hundred' ) );
document.write( getRandomNumber( 1000, 20000 ) );
document.write( getRandomNumber( 50, 100 ) );

This function will test if the arguments passed in are numbers. I completed and understood the challenge, but expected other results.

Here is my confusion: when you call the function for the first time it will throw an error. But why won't it continue to run the 2nd time the function is called? Why does the program stop after the first failed test?

2 Answers

Jennifer Mitchell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Mitchell
Full Stack JavaScript Techdegree Student 3,917 Points

There is no catch block in your code, so the program terminates. the MDN documentation does explain catch blocks, but that doesn't apply here.

Olga DC
Olga DC
16,680 Points

According to the MDN documentation: The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.