Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is Try or Catch in JavaScript?

In this blog post, we'll talk about a concept that's important when writing code in JavaScript, and is a feature commonly found in many programming languages. This concept is known as "try or catch," and it's a way to handle errors that might occur in your code. Now, don't feel intimidated by the jargon! By the end of this post, you'll have a solid understanding of what "try or catch" is, and how you can use it in your own code.

Understanding Errors

Before we dive into "try or catch," let's take a moment to understand what errors are in programming. When you write code, you'll inevitably encounter situations where something goes wrong. This could be due to a variety of reasons, such as incorrect user input, unexpected data, or even bugs in your code.

When these issues occur, they often result in errors. Errors are essentially the programming language's way of telling you that something went wrong and needs to be addressed. If errors are not handled properly, they can cause your program to crash, or behave in unexpected ways.

That's where "try or catch" comes in. It provides a way for you to handle these errors without causing your entire program to fail.

The Basics of Try or Catch

Now that we have a basic understanding of errors, let's dive into the concept of "try or catch" using some code examples.

Imagine you're writing a program that takes two numbers as input and divides them. Here's a simple function to perform this operation:

function divide(a, b) {
  return a / b;
}

This function works fine when given valid input. However, if the user were to input '0' as the second number (the divisor), you'd run into a problem: division by zero is undefined in mathematics, and attempting this operation in your code would result in an error.

This is where "try or catch" can help. You can use a "try" block to wrap the potentially error-prone code, and a "catch" block to handle the error if it occurs. Let's update our divide function to use "try or catch":

function divide(a, b) {
  try {
    return a / b;
  } catch (error) {
    console.error("An error occurred:", error);
  }
}

Now, if an error occurs while attempting to divide the numbers (such as dividing by zero), the "catch" block will be executed, and the error message will be printed to the console. This prevents the program from crashing or behaving unexpectedly.

It's important to note that the "catch" block receives an argument, which we've called error in our example. This argument contains information about the error that occurred, allowing you to take appropriate action based on the specific error.

Expanding on Try, Catch, and Finally

In addition to the "try" and "catch" blocks, there's another keyword that can be used in conjunction with them: "finally." The "finally" block contains code that will always be executed, regardless of whether an error occurred or not.

Here's an example of how you might use "finally" in our divide function:

function divide(a, b) {
  let result;

  try {
    result = a / b;
  } catch (error) {
    console.error("An error occurred:", error);
  } finally {
    console.log("The divide function was called.");
  }

  return result;
}

In this example, the "finally" block contains a simple console.log() statement, which will always be executed when the divide function is called. This can be useful for cleanup tasks or logging that should occur regardless of whether an error was encountered.

Error Types and Custom Errors

JavaScript has several built-in error types, such as TypeError, ReferenceError, and RangeError. These error types can be used to provide more specific information about the error that occurred. For example, if a user attempts to divide by zero, you might want to throw a RangeError with a helpful message.

Here's how you could modify the divide function to throw a custom error:

function divide(a, b) {
  if (b === 0) {
    throw new RangeError("You cannot divide by zero.");
  }

  return a / b;
}

Now, if the user attempts to divide by zero, a RangeError will be thrown with a helpful message. This error will then be caught and handled by the "catch" block, just like any other error.

Putting It All Together

Now that we've covered the basics of "try or catch," error types, and custom errors, let's take a look at a more complete example. In this example, we'll create a small program that prompts the user for two numbers and then divides them using our divide function.

function getInput(promptText) {
  const input = prompt(promptText);

  if (isNaN(input) || input === "") {
    throw new TypeError("Invalid input. Please enter a number.");
  }

  return parseFloat(input);
}

function main() {
  try {
    const num1 = getInput("Enter the first number:");
    const num2 = getInput("Enter the second number:");

    const result = divide(num1, num2);

    console.log(`The result of dividing ${num1} by ${num2} is ${result}.`);
  } catch (error) {
    console.error("An error occurred:", error);
  } finally {
    console.log("Thanks for using our program!");
  }
}

main();

In this example, we've created a getInput function that prompts the user for input and throws a TypeError if the input is not a valid number. Our main function then uses "try or catch" to handle any errors that might occur while getting the user's input or dividing the numbers.

Conclusion

In this blog post, we've covered the concept of "try or catch" in JavaScript, which is a way to handle errors that might occur in your code. We've learned about "try" and "catch" blocks, as well as the "finally" keyword, and how to use them in conjunction with built-in and custom error types.

By understanding and implementing "try or catch" in your code, you can create more robust and resilient programs that handle errors gracefully, providing a better user experience and preventing unexpected crashes or behavior.

Happy coding!