Error Handling

Implement try...catch blocks and handle errors effectively in your code.

Present State

JavaScript provides structured error handling through the try...catch statement. This allows developers to anticipate potential runtime errors and respond to them gracefully without crashing the entire application. Additionally, the finally block and custom error creation using throw enhance the robustness and clarity of error management in code.

Code Example

Here’s how you can use try...catch for error handling in JavaScript:

try...catch Example

function parseJSON(data) {
  try {
    const result = JSON.parse(data);
    console.log("Parsed successfully:", result);
  } catch (error) {
    console.error("Failed to parse JSON:", error.message);
  } finally {
    console.log("Parsing attempt complete.");
  }
}

parseJSON('{"name": "Alice"}');       // Valid JSON
parseJSON('{name: Alice}');           // Invalid JSON
          

This code demonstrates:

  • Using try to wrap potentially unsafe code.
  • Handling errors in the catch block.
  • Executing cleanup or final steps with finally.

Description

The try...catch construct allows developers to handle runtime errors:

  • try: Contains code that might throw an error.
  • catch: Executes if an error occurs in the try block. Provides access to the error object.
  • finally: (Optional) Always executes after try and catch, regardless of the outcome.

You can also use throw to create custom errors:

throw new Error("Custom error message");

Error handling is critical for creating resilient applications that can recover from unexpected issues gracefully.

Applications

  • Handling API response errors or invalid data formats.
  • Managing unexpected user inputs.
  • Preventing application crashes from runtime errors.
  • Adding graceful fallbacks for failed operations.
  • Logging or reporting issues for debugging purposes.

Multiple Choice Questions

Q1: What is the purpose of the catch block?

  • A. To execute code after try
  • B. To catch syntax errors
  • C. To handle runtime errors from try
  • D. To prevent code execution

Answer: C. To handle runtime errors from try

Q2: What happens if an error occurs in a try block without a catch?

  • A. The error is silently ignored
  • B. JavaScript throws a warning
  • C. The script halts or throws a runtime error
  • D. finally will catch it

Answer: C. The script halts or throws a runtime error

Q3: What does the finally block do?

  • A. Executes only if an error occurs
  • B. Executes after try and catch regardless of outcome
  • C. Prevents the error from being thrown
  • D. Logs the error

Answer: B. Executes after try and catch regardless of outcome

Q4: How do you throw a custom error in JavaScript?

  • A. error("message")
  • B. raise "message"
  • C. throw new Error("message")
  • D. throw.error("message")

Answer: C. throw new Error("message")