Error types

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

Built-in Error Types

JS · Error Handling
Syntax
TypeError | RangeError | ReferenceError | SyntaxError | URIError | EvalError | AggregateError
Example
// TypeError - wrong type for an operation
try { null.toString(); }
catch (e) { console.log(e.constructor.name); } // "TypeError"

// RangeError - value out of allowed range
try { new Array(-1); }
catch (e) { console.log(e.constructor.name); } // "RangeError"

// ReferenceError - undeclared variable
try { console.log(undeclaredVar); }
catch (e) { console.log(e.constructor.name); } // "ReferenceError"

Note Catching specific types helps you handle known errors differently from unexpected ones. AggregateError wraps multiple errors (used by Promise.any()).

PYPython

Common Built-in Exceptions

PY · Error Handling
Syntax
ValueError, TypeError, KeyError, IndexError, ...
Example
# ValueError - wrong value for the type
# TypeError - wrong type entirely
# KeyError - missing dictionary key
# IndexError - list index out of range
# AttributeError - missing attribute
# FileNotFoundError - file doesn't exist
# PermissionError - insufficient permissions
# StopIteration - iterator exhausted

try:
    open("nonexistent.txt")
except FileNotFoundError:
    print("File not found")
Output
File not found

Note Learn the hierarchy: FileNotFoundError is a subclass of OSError. Catching OSError also catches FileNotFoundError, PermissionError, etc.

Frequently asked questions

How does JavaScript handle error types?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Built-in Error Types" snippet in JavaScript uses `TypeError | RangeError | ReferenceError | SyntaxError | URIError | EvalError | Aggregat...`.
Which code does the JavaScript example use?
The "Built-in Error Types" snippet uses `TypeError | RangeError | ReferenceError | SyntaxError | URIError | EvalError | Aggregat...`, from the Error Handling section of the JavaScript cheat sheet.
Which stacks cover "error types" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Built-in Error Types": Catching specific types helps you handle known errors differently from unexpected ones. AggregateError wraps multiple errors (used by Promise.any()).