Sari la conținutul principal
← ⚡ JavaScript & the browser·Modul C7 · Lecția 2
SarcinăThrow a new TypeError('expected number') inside a function and catch it. Log err.name, err.message. Also log err.stack.length > 0 to confirm a stack is present (true/false).

The Error object — name, message, stack

75 XP6 min
Teorie

What's inside an Error

Every Error has three useful fields:

  • err.name — the class name ("Error", "TypeError", "RangeError", custom).
  • err.message — the first arg you passed to new.
  • err.stack — a multi-line string with the call stack at throw time.
const err = new TypeError("expected number");
err.name;     // "TypeError"
err.message;  // "expected number"
err.stack;    // "TypeError: expected number\n    at <anonymous>:1:13..."

Built-in error subclasses

JavaScript ships several subclasses you should reach for instead of bare Error:

  • TypeError — wrong type (e.g. called (undefined).foo).
  • RangeError — number/string outside valid range.
  • SyntaxError — thrown by JSON.parse on bad input.
  • URIError — decodeURIComponent on bad input.

Using the right subclass lets call sites narrow with instanceof (see C7-05).

🔒

Înregistrează-te pentru a începe să programezi

Teoria e accesibilă tuturor. Editorul, previzualizarea live și verificarea se deblochează cu o probă gratuită de 7 zile — card necesar, anulabilă oricând.

Înregistrare — probă gratuită →

Primele 10 lecții din fiecare traseu sunt gratis. Fără card.

← AnterioarăLecția următoare →

Primește un sfat Python sau web pe zi — prin email

Scurt, scris de mână, fără spam. Dezabonare cu un click.