Handling Errors with Try-Catch

Tutorial 4 of 5

Handling Errors with Try-Catch in JavaScript

1. Introduction

In this tutorial, we are going to explore how to handle errors in JavaScript using Try-Catch statements. This technique is a part of error handling mechanisms in JavaScript which can help you catch runtime errors before they crash your application and help to debug your application more effectively.

You will learn how to:

  • Understand the concept of Try-Catch in JavaScript.
  • Implement Try-Catch statements in your code.
  • Handle errors effectively in your application.

Prerequisites:

  • Basic knowledge of JavaScript programming.

2. Step-by-Step Guide

In JavaScript, the try..catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try..catch statement catches it.

The syntax is as follows:

try {
  // code here...
} catch(error) {
  // handle error here...
}
  • try: This keyword is used to specify the code that could potentially throw an error.
  • catch: This keyword is used to capture the error (if any) thrown inside the try block.

Best practices and tips:

  • It's always a good practice to handle exceptions in your application. This prevents your application from breaking and helps to maintain a good user experience.
  • Don't suppress the errors. Always log the errors to the console or to a file, this will help a lot in debugging the application.

3. Code Examples

Example 1:

try {
  // Trying to declare a variable with a reserved keyword
  let throw = 'test';
} catch(error) {
  console.log(error);
  // expected output: SyntaxError: Unexpected token 'throw'
}

In this example, we are trying to declare a variable with a reserved keyword, which results in a SyntaxError. The catch block captures this error and logs it to the console.

Example 2:

try {
  // Trying to access an undefined variable
  console.log(x);
} catch(error) {
  console.log(error);
  // expected output: ReferenceError: x is not defined
}

In this example, we are trying to access an undefined variable 'x', which results in a ReferenceError. The catch block captures this error and logs it to the console.

4. Summary

In this tutorial, you learned how to handle errors in JavaScript using Try-Catch statements. This is an important concept in JavaScript and can help to make your applications more robust and easier to debug.

Next steps for learning:

  • Understand the error handling in JavaScript in depth.
  • Learn about finally statement in JavaScript.
  • Learn about custom errors in JavaScript.

Additional resources:

5. Practice Exercises

Exercise 1: Write a function divide(a, b) that takes two parameters and returns the result of a / b. If b is 0, throw an error.

Solution:

function divide(a, b) {
  try {
    if(b == 0) {
      throw new Error("Division by zero not allowed");
    }
    return a / b;
  } catch(error) {
    console.log(error);
  }
}

divide(10, 0);
// expected output: Error: Division by zero not allowed

Exercise 2: Write a function getProp(obj, key) that takes an object and a key as parameters and returns the value of the key in the object. If the key is not present in the object, throw an error.

Solution:

function getProp(obj, key) {
  try {
    if(!obj.hasOwnProperty(key)) {
      throw new Error("Key not found in object");
    }
    return obj[key];
  } catch(error) {
    console.log(error);
  }
}

let obj = {name: 'John', age: 30};
getProp(obj, 'city');
// expected output: Error: Key not found in object

In both exercises, we're checking for a specific condition and if the condition is met, we throw an error which is then caught by the catch block.

Tips for further practice:

  • Try to create your own custom errors and use them in your code.
  • Learn about the finally statement and use it in your code.