bhylu.com

Advertisements

JS Error Statements

Throw signals a failure and try/catch handles it. Put the validation close to the operation that requires valid input.

Where to run this

This example uses the JavaScript console playground. Select Run to execute it; the example does not run on this lesson page.

A practical example

JavaScript

function book(count) {
  if (count < 1) throw new RangeError("Choose at least one place.");
  return count;
}
try { book(0); } catch (error) { console.log(error.message); }

What happens

The invalid booking produces a readable validation message.