Try, Catch & Finally

JavaScript's try...catch...finally structure lets you handle errors gracefully during code execution. It helps prevent your program from crashing by catching exceptions and running recovery code.

How It Works

  • try: Wraps the code block that might throw an error.
  • catch: Runs if an error occurs inside try. Receives the error object.
  • finally: Runs after try and catch, regardless of success or failure.

📌 Deep Dive: Basic Try-Catch

JAVASCRIPT
try {
  // Code that may throw an error
  let result = riskyOperation();
  console.log('Result:', result);
} catch (error) {
  console.log('Caught an error:', error.message);
}
Output (if error)
Caught an error: [error message]

Purpose of Each Block

Try, Catch & Finally Roles
BlockRole
tryRun code that might throw an error
catchHandle the error if one occurs
finallyRun cleanup or final code no matter what

📌 Deep Dive: Try-Catch-Finally

JAVASCRIPT
try {
  throw new Error('Oops!');
} catch (error) {
  console.log('Error caught:', error.message);
} finally {
  console.log('This runs always, cleanup here.');
}
Output
Error caught: Oops!
This runs always, cleanup here.
Illustration of try_catch_finally
Illustration of try_catch_finally

💡 Important

The catch block only runs if an error occurs inside try. The finally block runs regardless of errors.

Common Use Cases

  • Handling unexpected runtime errors without stopping the whole program.
  • Cleaning up resources (like closing files or network connections) in finally.
  • Providing user-friendly error messages.

⚠️ Avoid Empty Catch Blocks

Don't leave catch empty or ignore errors silently—it can hide problems making debugging harder.

Quick Syntax Summary

try {
  // risky code
} catch (error) {
  // error handling
} finally {
  // always runs
}