JavaScript Error Handling 2 — Questions and Answers
Question 1: What types of errors can be thrown in JavaScript?
- Only Error objects
- Any value including strings, numbers, and objects (Correct answer)
- Only subclasses of Error
- Only errors defined by the browser
Correct answer: Any value including strings, numbers, and objects
JavaScript's `throw` statement can throw any value — strings, numbers, objects, or Error instances. However, best practice is to throw Error objects or subclasses to preserve stack traces.
While `throw` accepts any value, throwing non-Error values has drawbacks: they don't carry a stack trace, and `catch (e)` will capture whatever you threw without standardized properties. Error objects have `message`, `name`, and `stack` properties. Custom errors should extend the `Error` class: `class CustomError extends Error { constructor(msg) { super(msg); this.name = 'CustomError'; } }`
Question 2: What is the purpose of the `finally` block in try/catch/finally?
- It runs only if an error was caught
- It runs only if no error occurred
- It always runs regardless of whether an error occurred (Correct answer)
- It re-throws any caught error
Correct answer: It always runs regardless of whether an error occurred
The `finally` block always executes after `try` and any applicable `catch` block, regardless of whether an error occurred or was caught. It's used for cleanup code.
`finally` runs even if there is a `return` statement in `try` or `catch`, and even if an error in `catch` throws again. If `finally` itself has a `return`, it overrides any previous `return`. Common uses: closing file handles, hiding loading spinners, releasing resources. If `finally` throws, that error replaces any previous error.
Question 3: What is a RangeError in JavaScript?
- An error when a variable is out of scope
- An error when a value is not within the allowed range (Correct answer)
- An error when accessing an array out of bounds
- An error from network request failures
Correct answer: An error when a value is not within the allowed range
A `RangeError` is thrown when a value is not within the allowed range. Examples: passing an invalid length to `new Array(-1)`, calling `toFixed()` with a number out of range, or infinite recursion causing a stack overflow.
Built-in JavaScript RangeError examples: `new Array(-1)` (negative array length), `(1.5).toFixed(200)` (digits out of range 0–100), `Number.prototype.toPrecision(0)`, and infinite recursion (`Maximum call stack size exceeded`). Unlike ReferenceError (undefined variable) or TypeError (wrong type), RangeError is about a valid type but invalid numeric value.
Question 4: How do you create a custom error type in JavaScript?
- Using `Error.create('CustomError')`
- By extending the `Error` class with `class CustomError extends Error {}` (Correct answer)
- By assigning a name property: `const err = { name: 'CustomError' }`
- Custom errors cannot be created in JavaScript
Correct answer: By extending the `Error` class with `class CustomError extends Error {}`
You create custom errors by extending the `Error` class. Call `super(message)` in the constructor, and set `this.name` to your custom error name for proper identification.
```js class ValidationError extends Error { constructor(message, field) { super(message); this.name = 'ValidationError'; this.field = field; } } ``` Then `throw new ValidationError('Required', 'email')`. In `catch`, you can check `e instanceof ValidationError`. Always set `this.name` because it defaults to `'Error'` otherwise, making error identification harder.
Question 5: What is the `Error.prototype.stack` property?
- A list of all errors thrown in the application
- A string containing the call stack at the time the error was created (Correct answer)
- The number of nested try/catch blocks
- An array of Error objects in a chain
Correct answer: A string containing the call stack at the time the error was created
The `stack` property is a string that contains the error message followed by the call stack (list of function calls) at the point where the error was created. It's invaluable for debugging.
The `stack` property is non-standard but supported by all major environments. It includes the error name, message, and each frame in the call stack with file name, line number, and column number. The format varies slightly between V8 (Node.js/Chrome), SpiderMonkey (Firefox), and JavaScriptCore (Safari). It's not guaranteed to be present in all environments.
Question 6: When does JavaScript throw a TypeError?
- When accessing a variable before it is declared
- When performing an operation on a value of the wrong type (Correct answer)
- When a numeric value is out of range
- When a module cannot be found
Correct answer: When performing an operation on a value of the wrong type
A `TypeError` occurs when an operation is performed on a value of an incompatible type. Common examples: calling a non-function as a function, accessing a property on `null` or `undefined`, or passing the wrong type to a function that expects a specific type.
TypeError examples: `null.property` (can't read property of null), `undefined()` (not a function), `const obj = {}; obj.push(1)` (push is not a function on plain objects). Accessing before declaration with `let`/`const` is a ReferenceError, not TypeError. ModuleNotFoundError is specific to Node.js and not a TypeError.
What types of errors can be thrown in JavaScript?