0
0
Javascriptprogramming~5 mins

Catching runtime errors in Javascript

Choose your learning style9 modes available
Introduction

Sometimes programs make mistakes while running. Catching runtime errors helps stop the program from crashing and lets you handle problems smoothly.

When reading a file that might not exist.
When asking a user for input that might be wrong.
When calling a function that might fail.
When working with data from the internet that might be missing or broken.
Syntax
Javascript
try {
  // code that might cause an error
} catch (error) {
  // code to handle the error
}

The try block contains code that might cause an error.

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

Examples
This example tries to divide by zero. JavaScript does not throw an error here, so catch is not triggered.
Javascript
try {
  let result = 10 / 0;
  console.log(result);
} catch (error) {
  console.log('Error caught:', error.message);
}
This example tries to parse invalid JSON, which causes an error caught by catch.
Javascript
try {
  JSON.parse('invalid json');
} catch (error) {
  console.log('Caught error:', error.message);
}
This example calls a function that does not exist, causing an error caught by catch.
Javascript
try {
  nonExistentFunction();
} catch (error) {
  console.log('Oops! Function not found.');
}
Sample Program

This program tries to read user input as JSON. Because the input is broken, it throws an error. The catch block catches it and prints 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('There was a problem parsing user input:', error.message);
}
OutputSuccess
Important Notes

Always use try...catch around code that might fail to keep your program running smoothly.

You can access the error message with error.message inside the catch block.

Use finally block if you want to run code no matter what, after try and catch.

Summary

Catching runtime errors helps your program handle problems without crashing.

Use try to run risky code and catch to handle errors.

This makes your program more friendly and reliable.