How to Handle Errors in JavaScript

In JavaScript
August 17, 2023

Various Errors

Runtime errors and syntax errors are the two basic forms of mistakes in JavaScript.

When the code does not follow the conventions of writing, a syntax error occurs. Syntax mistakes, for instance, might result from things like wrong variable names, missed parentheses, or improper punctuation placement.

Runtime problems occur during execution even when the code appears to be correct. Runtime errors include things like undefined variables, inappropriate function use, and carrying out erroneous operations, for example.

Try-Catch

The JavaScript try keyword is employed to runtime test the code contained within a code block.

Errors originating from runtime issues are displayed using the JavaScript catch keyword.

JavaScript mistakes are manageable using try and catch.

try {
//Code block to be executed for testing
}
catch(e) {
//Code block to be executed if an error occurs
}"

Throws

The efficient execution of a program can be hampered by errors that happen when JavaScript code is active. The ‘throw’ keyword enables us to recognize these issues and handle them with tailored messages. Using “throw” in an error condition causes the program to stop running and generates the supplied error message.

Each mistake is produced as an “Error” object with the values “name” and “message.” ‘name’ identifies the error’s category, whereas message gives the error’s justification.

By utilizing the ‘throw’ keyword, we may design our own mistakes. Because of this, we are able to create our own error scenarios and messages. Text, numbers, logic, and objects may all be used as different forms of errors.

The resilience and reliability of the code are improved through error handling. The ‘throw’ keyword and error objects give programmers the opportunity to handle unforeseen circumstances and produce more informative error messages. Our programming provides a more smooth and user-friendly experience as a consequence.

<script>
  var studentGrade = prompt("Please enter the student's grade:");

  try {
    if (studentGrade === "") throw "You did not enter a grade!";
    studentGrade = Number(studentGrade);

    if (isNaN(studentGrade)) throw "Please enter a valid number!";
    if (studentGrade < 0 || studentGrade > 100) throw "Grade must be between 0 and 100";

    if (studentGrade < 50) {
      throw "Student failed!";
    } else if (studentGrade >= 50 && studentGrade < 70) {
      throw "Student passed, but with a moderate grade.";
    } else {
      throw "Student passed, excellent work!";
    }
  } catch (error) {
    alert("Error: " + error);
  }
</script>

Finally

The ‘finally’ keyword in JavaScript facilitates the end of the function and its execution in both cases, promoting more secure and organized code writing.

The ‘finally’ keyword allows us to specify code blocks that will be performed whether or not there is a bug in the JavaScript code. This helps with chores like cleanup and resource release, making sure that regardless of the result, the code is finished neatly or the resources are appropriately released.

function divideNumbers(a, b) {
  try {
    if (b === 0) {
      throw new Error("Division by zero is not allowed.");
    }
    return a / b;
  } catch (error) {
    console.error("Error Caught:", error.message);
    return null;
  } finally {
    console.log("Division operation completed.");
  }
}

console.log(divideNumbers(10, 2));  // Result: 5
console.log(divideNumbers(10, 0));  // Error Caught: Division by zero is not allowed. / Division operation completed.
console.log(divideNumbers(8, 2));   // Result: 4

EvalError 

Describes mistakes that happen while using JavaScript’s eval() function. The given text is translated into code using the eval() method. JavaScript throws an EvalError if the provided code is not a valid JavaScript expression or code snippet and contains confusing or incorrect statements.

Range Error

The specified JavaScript code and error message are translated as follows: In the event that the JavaScript number limit is exceeded, a RangeError is generated.

<script>
  var value = 0;
  try {
    value.toPrecision(1000);
  }
  catch(exception) {
    alert("Exception Type: " + exception.name);
    alert("Exception Message: " + exception.message)
  }
</script>

Reference Errors

When a variable or object is attempted to be referenced to a location where it does not exist, this sort of error occurs. This frequently occurs when you try to access an object’s attributes or methods or when you name a variable incorrectly. You should carefully study and create your code by predefining your variables and objects in order to avoid making mistakes of this nature.

name = "Amelie"
print(names)  # 'names' not defined, getting Reference Error

var person = {
    firstName: "Amelie",
    lastName: "Flow"
};
console.log(person.age); // 'age' property not defined, getting Reference Error

TypeError

When an action is carried out that is incompatible with distinct data types, a TypeError is generated. This error, for instance, can occur if you try to apply a string method to a number or if you try to combine several data types in an unworkable way. Using the toUpperCase() function, we are attempting to convert an integer to uppercase in the example provided. However, attempting to use this function on a number would result in a TypeError because it is often used on string data types.

var number = 5;
var text = "hello";

try {
    var result = number.toUpperCase(); // Attempting to convert a number to uppercase
    console.log(result);
} catch (error) {
    if (error instanceof TypeError) {
        console.error("Error: " + error.message);
    } else {
        console.error("An unknown error occurred: " + error.message);
    }

URIError (URI Error)

URIError is used when an error occurs in functions like encodeURI() or decodeURI(). These types of errors commonly occur in operations related to Uniform Resource Identifiers (URIs).

We are attempting to decode an improperly encoded URI using the decodeURI() function. When attempting to decode incorrectly encoded URIs, we receive a URIError.

try {
    var decodedURI = decodeURI("%%"); // Attempting to decode a improperly encoded URI
    console.log("Decoded URI: " + decodedURI);
} catch (error) {
    if (error instanceof URIError) {
        console.error("Error: " + error.message);
    } else {
        console.error("An unknown error occurred: " + error.message);
    }
}