JavaScript – Errors & Exceptions Handling

By Published 3 min read

JavaScript is a versatile and widely used programming language in web development. However, like any other programming language, it’s not immune to errors and exceptions. Understanding how to handle these errors effectively is crucial for writing robust and reliable JavaScript code. In this blog, we’ll delve into the world of JavaScript errors and exceptions, exploring common types, best practices for handling them, and real-world examples to illustrate each concept.

What Are JavaScript Errors?

JavaScript errors are issues that occur during the execution of your code, preventing it from running as expected. These errors can result from various causes, including syntax mistakes, logic errors, or unexpected conditions during runtime. JavaScript categorizes errors into two main types: syntax errors and runtime errors.

1. Syntax Errors

Syntax errors, also known as parsing errors, occur when you write code that doesn’t adhere to the language’s syntax rules. These errors are detected by the JavaScript parser during compilation, and the code won’t execute until you correct them. Here’s an example of a syntax error:

let x = 10;
console.log(x)Code language: JavaScript (javascript)

In the code above, there’s a missing semicolon after console.log(x), which is a syntax error. The parser will throw an error, and the program won’t run until you fix it.

2. Runtime Errors

Runtime errors, also known as exceptions, occur during the execution of your code when something unexpected happens. These errors are not detected during compilation but at runtime when a specific condition is met. Common examples include:

  • Trying to access a property of an undefined variable.
  • Dividing by zero.
  • Calling a function that doesn’t exist.

Handling JavaScript Errors

Now that we understand the types of JavaScript errors let’s explore how to handle them effectively:

1. Try-Catch Statement

The try-catch statement is the most common way to handle exceptions in JavaScript. It allows you to wrap code that might throw an exception inside a try block and specify what to do if an exception occurs in the catch block. Here’s an example:

try {
  // Code that might throw an exception
  let result = x / y;
  console.log(result);
} catch (error) {
  // Handle the exception
  console.error('An error occurred:', error.message);
}Code language: JavaScript (javascript)

In this example, if the division by zero occurs, it will throw an exception, and the catch block will handle it, preventing the program from crashing.

2. Throw Your Own Errors

You can also create and throw custom errors using the throw statement. This is helpful when you want to provide meaningful error messages or define specific error types for your application. Here’s an example:

function divide(x, y) {
  if (y === 0) {
    throw new Error('Division by zero is not allowed');
  }
  return x / y;
}

try {
  let result = divide(10, 0);
  console.log(result);
} catch (error) {
  console.error('An error occurred:', error.message);
}Code language: JavaScript (javascript)

In this case, we’ve defined a custom error message for the division by zero scenario.

3. Finally Block

You can use the finally block to execute code regardless of whether an exception was thrown or not. This is often used for cleanup operations. For example:

try {
  // Code that might throw an exception
} catch (error) {
  // Handle the exception
} finally {
  // Code to run regardless of an exception
}Code language: JavaScript (javascript)

Common Types of JavaScript Errors

To gain a better understanding, let’s explore some common types of runtime errors in JavaScript and how to handle them:

a. TypeError

A TypeError occurs when you try to perform an operation on a value of the wrong type. For example:

let x = null;
let y = 10;

try {
  let result = x.toUpperCase(); // TypeError: x.toUpperCase is not a function
  console.log(result);
} catch (error) {
  console.error('An error occurred:', error.message);
}Code language: JavaScript (javascript)

To handle TypeError, you can check the type of the variable before performing operations on it.

b. ReferenceError

A ReferenceError occurs when you try to access a variable or function that hasn’t been declared or is out of scope. For example:

try {
  let result = divide(10, 5); // ReferenceError: divide is not defined
  console.log(result);
} catch (error) {
  console.error('An error occurred:', error.message);
}Code language: JavaScript (javascript)

To handle ReferenceError, ensure that the variable or function is declared and in scope.

Conclusion

JavaScript errors and exceptions are an integral part of programming, and understanding how to handle them is crucial for building reliable and robust applications. By using try-catch statements, throwing custom errors, and knowing how to handle common error types like TypeError and ReferenceError, you can write JavaScript code that gracefully handles unexpected situations.

Remember that effective error handling not only prevents your application from crashing but also provides valuable information for debugging and improving your code. So, the next time you write JavaScript code, don’t forget to consider error handling as an essential part of your development process.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume