← Back to Chapters

JavaScript Error Handling: try, catch, finally

⚠️ JavaScript Error Handling: try, catch, finally

? Quick Overview

Error handling in JavaScript lets your programs respond gracefully to unexpected situations instead of crashing. The main building blocks are try, catch, and finally, which work together to detect errors, handle them safely, and perform cleanup tasks.

? Key Concepts

  • try – Wraps code that might throw an error during execution.
  • catch – Runs only if an error occurs inside the try block and receives an error object.
  • finally – Always runs after try/catch, whether an error happened or not.
  • Error object – Holds details like name, message, and often stack for debugging.
  • Built-in errors – Examples include ReferenceError, TypeError, and SyntaxError.
  • Custom errors – You can create your own using throw and new Error().

? Syntax / Theory

A complete error-handling structure usually looks like this:

? View Code Example
try {
// Code that might throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that always runs (optional)
}

The JavaScript engine executes the try block first. If everything works, it skips directly to finally (if present). If an error is thrown inside try, control jumps to catch, then finally to finally.

? Code Examples

? Example: Only try Block

Here, we just run a risky operation. If it throws an error, it will stop the script unless handled somewhere else.

? View Code Example
try {
let result = riskyOperation();
console.log(result);
}

? Example: try with catch

Now we add catch to safely handle any error that occurs in the try block.

? View Code Example
try {
let result = riskyOperation();
console.log(result);
} catch (error) {
console.error("An error occurred:", error.message);
}

? Example: try, catch, and finally

The finally block runs after try/catch regardless of success or failure.

? View Code Example
try {
let result = riskyOperation();
console.log(result);
} catch (error) {
console.error("An error occurred:", error.message);
} finally {
console.log("This runs no matter what");
}

? Example: Custom Error with throw

You can validate input and throw a custom error when something is wrong.

? View Code Example
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}

try {
const result = divide(10, 0);
console.log("Result:", result);
} catch (error) {
console.error("Division failed:", error.message);
} finally {
console.log("Division attempt finished");
}

? Live Output & Explanation

? Live Demo: Validate a Number

Enter a value. The script will try to convert it to a number. If it is not a valid number, a custom error is thrown and handled in catch.

If the input is not a valid number, an error message will be shown.

 

? Use Cases / When to Use

  • When calling APIs or performing network requests that may fail.
  • When working with user input that might be invalid or unexpected.
  • When reading/writing files or using browser storage where access might fail.
  • When you need to ensure resources are cleaned up (closing connections, clearing timers) in finally.

? Tips & Best Practices

  • Wrap only the code that can actually throw an error inside try to keep error handling precise.
  • Always handle errors in catch instead of leaving it empty — at least log something meaningful.
  • Use finally for cleanup logic that must always run, such as closing connections or clearing intervals.
  • Log error.message (and error.stack in development) to make debugging easier.
  • Avoid putting core business logic only in finally; it should mainly be used for cleanup.

? Try It Yourself

  • Create a function that throws an error if the input is not a number, and handle it with a try-catch block.
  • Use finally to log "Operation completed" regardless of success or error.
  • Experiment with throw new Error("Custom message") and observe how catch receives it.
  • Modify the live demo to also reject negative numbers and show a different error message.