0
0
Javascriptprogramming~5 mins

Try–catch block in Javascript

Choose your learning style9 modes available
Introduction

A try-catch block helps your program handle errors without stopping. It lets you try some code and catch problems if they happen.

When reading a file that might not exist.
When asking for data from the internet that might fail.
When converting user input that might be wrong.
When running code that depends on other code working right.
Syntax
Javascript
try {
  // code that might cause an error
} catch (error) {
  // code to handle the error
}

The try block runs code that might fail.

The catch block runs only if there is an error in try.

Examples
This tries to divide by zero, but JavaScript does not throw an error here, so catch is not used.
Javascript
try {
  let result = 10 / 0;
  console.log(result);
} catch (error) {
  console.log('Error caught:', error.message);
}
This tries to read bad JSON text and catches the error to show a message.
Javascript
try {
  JSON.parse('bad json');
} catch (error) {
  console.log('Parsing failed:', error.message);
}
Sample Program

This program tries to read a broken JSON string. The catch block runs because the JSON is invalid, and it shows a friendly message.

Javascript
try {
  let userInput = '{"name": "Alice"'; // missing closing brace
  let user = JSON.parse(userInput);
  console.log('User name:', user.name);
} catch (error) {
  console.log('Oops! Invalid JSON:', error.message);
}
OutputSuccess
Important Notes

Only errors inside the try block are caught.

You can use error.message to get a simple description of the problem.

Try-catch blocks help keep your program running even if something goes wrong.

Summary

Use try to run code that might fail.

Use catch to handle errors and keep your program safe.

This makes your programs more friendly and reliable.