Next →

Handling Errors in JavaScript

Errors can occur during code execution. The try...catch statement lets you handle these errors gracefully without breaking your program.

Basic try/catch Structure

try {
  // Code that might throw an error
  let result = riskyFunction();
  console.log(result);
} catch (error) {
  // Handle the error
  console.error("An error occurred:", error.message);
}

Using finally

try {
  // Code that might throw
} catch (e) {
  console.error(e);
} finally {
  console.log("This runs regardless of error");
}