JSE Certified Entry-Level JavaScript Programmer study materials
JSE Certified Entry-Level JavaScript Programmer study resources

JSE Certified Entry-Level JavaScript Programmer: Error Handling and Debugging

JSE Certified Entry-Level JavaScript Programmer · Work through your exam, one topic at a time.

All guide sections

Error Handling and Debugging

What this domain covers

Recognising which built-in error type a bug produces, writing try/catch/finally correctly, creating custom errors, and using the console and stack traces to locate a fault.

Error types

  • SyntaxError - thrown at parse time; a syntax error in the current file cannot be caught by that file's own try/catch.
  • ReferenceError - undeclared identifier, or a let/const read before declaration.
  • TypeError - calling a non-function, or reading a property of undefined/null.
  • RangeError - invalid array length or an invalid toFixed digit count.

Every Error carries name, message, and stack.

try / catch / finally

catch receives the thrown value; the binding is optional (catch {}). finally runs whether the block threw, returned, or completed - and a return inside finally silently overrides the earlier return. throw can throw any value, but throwing Error instances keeps stack traces.

Custom errors and async code

Extend Error, call super(message), and set this.name. In async code, an un-awaited rejected promise escapes try/catch; you must await it or attach .catch.

Worked example

function parse(s) {
  try { return JSON.parse(s); }
  catch (e) { console.log(e.name); return null; }
  finally { console.log('done'); }
}
console.log(parse('{bad'));
console.log(parse('{"a":1}'));

Reasoning: the first call throws a SyntaxError from JSON.parse; the catch logs SyntaxError and returns null, but finally prints done before the value leaves the function. The second call returns the object, and finally still prints done.

Traps

  • Expecting one try around many statements to tell you which statement failed.
  • Logging a thrown non-Error value and assuming message exists.
  • Placing finally before catch, which is illegal ordering.
  • Leaving a debugger; statement in shipped code.