JavaScript Error Handling: Try Catch Throw Finally

try {
    //statements that may cause an error
    }
catch (err) { //err holds info about the error
    //statements that handle an error, if one happens
    throw err //if you decide to error after all
    }
finally { //optional
    //statements that happen error or not
    }

There are 3 types of errors:

  1. Programmer messed up. Common.
  2. Programmer didn't catch every possible case of bad data, and bad data causes an error. Occasional.
  3. Programmer made no mistakes and the machine choked. Very very rare.

#1 is corrected by the programmer learning and fixing the code. #2 can be fixed by adding more code to better check the data, but it starts to get annoying... #3 can't be fixed... except by a try-catch block. And, they really manes dealing with bad data easy. Just don't deal with it, and reject anything that causes a crash.

The catch block can example the error object and take action based on the type of the error. e.g.

try {
  something();
} catch (e) {
  if (e instanceof RangeError) {
    // statements to handle this very common expected error
    console.log("out of range"+e)
    throw "value out of range"
  } else {
    throw e;  // re-throw the error unchanged
  }
}

The error object also has two attributes: .name which is the general class of error, and .message which is a short error message.

Error classes include:

The throw keyword accepts any expression, or can be used with new to make a new error object of any error class or a generic error. E.g.

throw "bogus" //directly using a string or other value
throw my_error_messages(32) //function can return a value for the error
throw new Error("bogus") //generic error with message
throw new TypeError("value must be a widget") //error of type TypeError

See also: