Handle errors with try / catch

Catch problems you can handle, throw clear errors for the rest.

JavaScript · Handle errors with try / catchBeginner
function toAge(value) {
  const n = Number(value);
  if (!Number.isInteger(n) || n < 0 || n > 120) {
    throw new RangeError('Age must be a whole number from 0 to 120');
  }
  return n;
}

let message = '';
try {
  toAge('abc');
} catch (err) {
  message = err.message;                   // show this to the user
} finally {
  // runs always
}
errortrycatchthrow