0
0
Node.jsframework~5 mins

Try-catch for synchronous errors in Node.js

Choose your learning style9 modes available
Introduction
Try-catch helps you catch and handle errors that happen while your code runs, so your program doesn't crash unexpectedly.
When you want to safely run code that might cause an error, like reading a file or parsing data.
When you want to show a friendly message instead of a crash if something goes wrong.
When you want to log errors for debugging without stopping the whole program.
When you want to try multiple steps and handle errors in each step separately.
Syntax
Node.js
try {
  // code that might throw an error
} catch (error) {
  // code to handle the error
}
The code inside try runs normally unless an error happens.
If an error happens, the code inside catch runs with the error details.
Examples
This example tries to divide by zero. In JavaScript, this does not throw an error, so catch won't run.
Node.js
try {
  let result = 10 / 0;
  console.log(result);
} catch (error) {
  console.log('Error caught:', error.message);
}
This example tries to parse invalid JSON, which throws an error caught by catch.
Node.js
try {
  JSON.parse('invalid json');
} catch (error) {
  console.log('Parsing failed:', error.message);
}
This example calls a function that does not exist, causing an error caught by catch.
Node.js
try {
  nonExistentFunction();
} catch (error) {
  console.log('Function error:', error.message);
}
Sample Program
This program tries to parse two JSON strings. The first is valid and prints the name. The second is invalid and throws an error, which is caught and logged. The program then continues.
Node.js
try {
  const data = JSON.parse('{"name": "Alice"}');
  console.log('Name:', data.name);
  const brokenData = JSON.parse('bad json');
  console.log('This line will not run');
} catch (error) {
  console.log('Caught an error:', error.message);
}
console.log('Program continues running');
OutputSuccess
Important Notes
Try-catch only works for errors that happen inside the try block during synchronous code execution.
Errors in asynchronous code (like callbacks or promises) need different handling methods.
Always keep try blocks small to catch errors precisely and avoid hiding bugs.
Summary
Try-catch lets you handle errors without crashing your program.
Use try-catch around code that might throw errors during normal running.
Catch block receives the error object to help you understand what went wrong.