Error Handling

Catching an error prevents the execution from halting as a result of the error. Errors are caught within try{...} and handled in catch(e){...} (the (e) clause has become optional for catch.) The finally{...} clause will always be executed, even if there is no error.

This example tries to call a function that is not defined. The resulting error is captured by the error object err.
RESETRUNFULL
<!DOCTYPE html><html><body><script>

<!DOCTYPE html><html><head></head><body><script>
   try {
      asdd(5);
   } catch(err){
      document.write(err.message);
   } finally {
      document.write(".");
   }
   document.write(" program not halted.");   // asdd is not defined. program not halted.</script></body></html>

</script></body><html>
We can throw our own errors. Uncaught errors halt the program.
RESETRUNFULL
<!DOCTYPE html><html><body><script>

<!DOCTYPE html><html><head></head><body><script>
   try {
      var a=0;
      if (a==0) throw "Division by zero.";
      document.write(5/a);
   } catch(err){
      document.write(err);
   }
   throw "MyError";  // program halted here
   document.write("program halted.");   // Division by zero.</script></body></html>

</script></body><html>

Seven Objects inherit from Error: EvalError, InternalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError. The inherited properties are: .message, .name, .fileName, .lineNumber, .columnNumber, and .stack.


RESETRUNFULL
<!DOCTYPE html><html><body><script>

try {
  var a = undefinedVariable;} catch (e) {
  console.log(e instanceof ReferenceError); // true
  console.log(e.message); // "undefinedVariable is not defined"
  console.log(e.name);                // "ReferenceError"
  console.log(e.fileName);            // "MyFile/1"
  console.log(e.lineNumber);        // 2
  console.log(e.columnNumber);   // 6
  console.log(e.stack);                 // "@ MyFile/2:2:7\n"}

</script></body><html>