JavaScript Errors


Error handling in JavaScript refers to the process of catching and managing errors that occur during the execution of a program to prevent crashes or unexpected behavior. JavaScript provides mechanisms for developers to catch errors and handle them gracefully, so they don’t disrupt the entire application.

In JavaScript, there are several built-in error types that represent different kinds of errors that can occur during the execution of a program. Each error type has its own meaning and use case. Here are the main types of errors in JavaScript:

1. Error

The Error object is the base object for all error types. It can be used to create a general error that doesn’t fall under any specific category.

try {
  throw new Error(‘This is a general error’);
} catch (error) {
  console.error(error.name); // Output: Error
  console.error(error.message); // Output: This is a general error
}


2. SyntaxError

A SyntaxError is thrown when there is a syntax mistake in the code, making it invalid JavaScript. This type of error is typically caught during the parsing stage.

try {
  eval(‘foo bar’); // Invalid JavaScript code
} catch (error) {
  console.error(error.name); // Output: SyntaxError
  console.error(error.message); // Output: Unexpected identifier
}

 

3. ReferenceError

A ReferenceError is thrown when trying to reference a variable that has not been declared.

try {
  console.log(nonExistentVariable);
} catch (error) {
  console.error(error.name); // Output: ReferenceError
  console.error(error.message); // Output: nonExistentVariable is not defined
}

 

4. TypeError

A TypeError is thrown when a value is not of the expected type. For example, trying to call a non-function or accessing a property of undefined or null.

try {
  let person = null;
  console.log(person.name);
} catch (error) {
  console.error(error.name); // Output: TypeError
  console.error(error.message); // Output: Cannot read property ‘f’ of null
}

 

5. RangeError

A RangeError is thrown when a value is not within the set or expected range. For example, passing an invalid length to an array.

try {
  const arr = new Array(-1); // Invalid array length
} catch (error) {
  console.error(error.name); // Output: RangeError
  console.error(error.message); // Output: Invalid array length
}

 

6. URIError

A URIError is thrown when there is an error in encoding or decoding the URI (Uniform Resource Identifier). This usually occurs with encodeURI(), decodeURI(), encodeURIComponent(), or decodeURIComponent() functions.

try {
  decodeURIComponent(‘%’); // Invalid URI sequence
} catch (error) {
  console.error(error.name); // Output: URIError
  console.error(error.message); // Output: URI malformed
}

 

7. EvalError

An EvalError is thrown when there is an error related to the eval() function. Although this error type is still part of the language, it is not thrown by the JavaScript engine anymore but remains for backward compatibility.

try {
  throw new EvalError(‘This is an eval error’);
} catch (error) {
  console.error(error.name); // Output: EvalError
  console.error(error.message); // Output: This is an eval error
}

 

Error Handling with try…catch

JavaScript provides a try…catch block to handle errors that occur during runtime. The try…catch statement in JavaScript is used to handle exceptions and manage errors. It allows you to run a block of code and handle any errors that occur without crashing the entire application. Here’s a basic example:

try {

    // Code that may throw an error
    let result = riskyOperation();
    console.log(result);

} catch (error) {

    // Code to handle the error
    console.error(‘An error occurred:’, error.message);

} finally {

    // Code that will run regardless of whether an error occurred
    console.log(‘The try…catch block has finished executing.’);

}

Components of try…catch

1. try block: Contains the code that might throw an error.

2. catch block: Contains code that handles the error. The error object is automatically passed to this block, and you can use it to get information about the error.

3. finally block (optional): Contains code that will execute after the try and catch blocks, regardless of whether an error was thrown or caught.

Example

function divide(a, b) {
    if (b === 0) {
        throw new Error(‘Division by zero is not allowed.’);
    }
    return a / b;
}
try {
    let result = divide(10, 0);
    console.log(‘Result:’, result);
} catch (error) {
    console.error(‘Caught an error:’, error.message);
} finally {
    console.log(‘Execution completed.’);
}

In this example:

• The divide function throws an error if an attempt is made to divide by zero.

• The try block calls the divide function and may throw an error.

• The catch block catches and logs the error.

• The finally block logs a message indicating that execution is complete, regardless of whether an error occurred.

 
 

Scroll to Top