Skip to main content

JavaScript Error Handling

By SamK
0
0 recommends
Category(s)
Topic(s)

Error handling in JavaScript ensures that the program continues to run smoothly even when errors occur. There are multiple techniques to handle errors effectively.

  • try: Defines a block of code to test for potential errors.
  • catch: Handles any error that occurs in the try block.
  • finally: Executes code after try and catch, regardless of whether an error occurred.
  • throw: Allows you to generate custom errors.

Errors are Inevitable

Errors can occur due to programming mistakes, incorrect input, or other unforeseen issues.

Example

In this example, we deliberately introduce a misspelled function to trigger an error.

//  Handling an Error
try {
 adddlert("Welcome guest!"); // Intentional error
} catch (err) {
 console.log("Error:", err.message); // Output: Error: adddlert is not defined
}

JavaScript Try and Catch

The try block lets you test a block of code for errors, while the catch block handles them.

try {
 let num = 5 / 0; // No error, but results in Infinity
 console.log("Result:", num);
} catch (err) {
 console.log("Error:", err.message); // Output: Result: Infinity
}

Throwing Custom Errors

JavaScript throws an exception when an error occurs, but you can define your own using `throw`.

function checkNumber(num) {
 if (num > 10) {
   throw "Number too large";
 }
 return "Valid number";
}
try {
 console.log(checkNumber(15));
} catch (err) {
 console.log("Error:", err); // Output: Error: Number too large
}

Input Validation Example

This script checks user input and throws custom errors for invalid values.

function validateInput() {
 const input = document.getElementById("demo").value;
 const message = document.getElementById("output");
 message.innerHTML = "";
 
 try {
   if (input.trim() === "") throw "Input is empty"; 
   if (isNaN(input)) throw "Not a number";
   let num = Number(input);
   if (num < 5) throw "Number too low";
   if (num > 10) throw "Number too high";
 } catch (err) {
   message.innerHTML = "Error: " + err;
 } finally {
   document.getElementById("demo").value = "";
 }
}

/*
Input: ""; Output: Error: Input is empty
Input: "abc"; Output: Error: Not a number
Input: 3;  Output: Error: Number too low
Input: 12; Output: Error: Number too high
Input: 7; Output: Valid input: 7
*/

Common JavaScript Errors

ReferenceError

Occurs when referring to an undefined variable.

try {
 console.log(myVar);
} catch (err) {
 console.log("Error:", err.name); // Output: Error: ReferenceError

TypeError

Occurs when a value is not of the expected type.

try {
 let num = 10;
 num.toUpperCase();
} catch (err) {
 console.log("Error:", err.name); // Output: Error: TypeError
}

SyntaxError

Occurs when the syntax of the code is incorrect.

try {
 eval("console.log('Hello)"); // Missing closing quote
} catch (err) {
 console.log("Error:", err.name); // Output: Error: SyntaxError
}

RangeError

Occurs when a number is outside of its allowable range.

try {
 let num = 1;
 num.toPrecision(500);
} catch (err) {
 console.log("Error:", err.name); // output: Error: RangeError
}

URIError

Occurs when illegal characters are used in URI functions.

try {
 decodeURI("%%%");
} catch (err) {
 console.log("Error:", err.name); // Output: Error: URIError

Questions & Answers