Using and catching RangeError in javascript

javascript, try-catch

Solution

try {
  saveNumber(...);
} catch (e) {
  if (e instanceof TypeError) {
    // ignore TypeError
  } 
  else if(e instanceof RangeError) {
    // handle RangeError
  }
  else {
    // something else
  } 
}

source

Problem

I'm about to throw an exception using RangeError and wanted to check that I'm using it correctly and how to best catch it. I have a function that could throw a RangeError OR a TypeError like this ``` function saveNumber(val) { // Only accept numbers. if (typeof val !== 'number') { throw new TypeError(); } // Error if the number is outside of the range. if (val > max || val < min) { throw new RangeError(); } db.save(val); } ``` I'd like to call it and only deal with the RangeError. What's the best way to do this?

Original source

Related problems