English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript basic tutorial

JavaScript object

JavaScript function

JS HTML DOM

JS browser BOM

AJAX basic tutorial

JavaScript reference manual

JavaScript Error Handling

Unexpected errors may occur when executing JavaScript code.

Errors can be coding errors made by programmers, errors caused by input errors, and other unforeseen events.

Therefore, to handle errors, JavaScript provides4A keyword:

  • The 'try' statement allows you to test if a code block contains errors

  • The 'catch' statement allows you to handle errors

  • The 'throw' statement allows you to create custom errors

  • The 'finally' statement allows you to execute code after a try and catch, regardless of the outcome

In this example, we have written 'alert' as 'aaalert' to intentionally cause an error:

try {
aaalert("Hello world");
}
document.getElementById("result").innerHTML = e.name + "<br>" + e.message;
}
Test See‹/›

When an error occurs, JavaScript usually stops running and creates an object with two propertiesError object: name and message.

JavaScript try ... catch statement

The 'try' statement allows you to define a block of code that will be tested for errors during execution.

The 'catch' statement allows you to define a block of code to be executed if an error occurs within a 'try' block.

JavaScript statements try and catch appear in pairs:

try {
  //try_statements-Attempted statements
}catch(err){
  //catch_statements-Error handling statements
}

JavaScript throw statement

throw statement throws a user-defined exception.

The throw statement allows you to create custom errors. Technically, this is called a "Throw an exception ".

Exceptions can be JavaScript strings, numbers, boolean values, or objects:

  throw "Invalid";  // Generate an exception with a string value
  throw 32;   // Generate a value of32The exception
  throw true;   // Generate an exception with a value of true

When throw is used with try and catch, you can specify the program flow and generate a custom error message.

In this example, if any non-numeric parameter is passed, the getRectArea() will throw a custom error:

function getRectArea(width, height) {
   if (isNaN(width) || isNaN(height)) {
  throw "Parameter is not a number!";
   }
}
try {
   getRectArea(5, 'Z');
}
catch(err) {
   document.getElementById('para').innerHTML = err;
}
Test See‹/›

Input validation example

In this example, if the value is incorrect, an exception (err) is thrown. The catch statement catches the exception (err) and displays a custom error message:

var x = document.querySelector("input").value;
try {
   if(x == "") throw "is Empty";
   if(isNaN(x)) throw "Not a Number";
   if(x > 10) throw "too High";
   if(x < 5)throw "too Low";
}
catch(err) {
   document.getElementById("para").innerHTML = "Input " + err;
}
Test See‹/›

JavaScript final statement

The finally statement allows you to execute code after try and catch, regardless of the result.

try {
   aaalert("Hello world");
}
catch(err) {
   document.getElementById("result").innerHTML = err;
}
finally {
   document.getElementById("result").innerHTML += "<h3>Finally statement executed</h3>";
}
Test See‹/›

catch and finally statements are optional, but you need to use one (and not both) of them, while using the try statement:

try {
   aaalert("Hello world");
}
finally {
   document.getElementById("result").innerHTML = "Finally statement executed";
}
Test See‹/›

JavaScript Error Object

JavaScript has a built-in Error object that provides error information when an error occurs.

The Error object provides two useful properties: name and message.

Error Object Properties

The following table lists the properties of the Error object:

PropertyDescription
nameSets or returns the error name
messageSets or returns the error message

Error Type

The 'name' property of the error can return seven different values:

TypeDescription
EvalErrorIt indicates errors related to the global function eval()
InternalErrorIt indicates an error that occurs when an internal error is triggered in the JavaScript engine
RangeErrorIt indicates an error that occurs when a numeric variable or parameter is out of its valid range
ReferenceErrorIt indicates an error that occurs when dereferencing an invalid reference
SyntaxErrorIt indicates a syntax error that occurs when parsing code in eval()
TypeErrorIt indicates an error that occurs when a variable or parameter is not a valid type
URIErrorIt indicates an error that occurs when passing invalid parameters to encodeURI() or decodeURI()

The next section will introduce each of these error types in more detail.

EvalError

When througheval()An EvalError will be thrown when an error occurs during the execution of a function.

However, JavaScript no longer throws this error, but it still retains this object for backward compatibility.

Newer versions of JavaScript do not throw an exception EvalError. SyntaxError is used instead.

RangeError

A RangeError will be triggered when a number is used outside the allowed value range.

For example, creating an array with a negative length will throw a RangeError:

try {
var arr = new Array(-1); // throws a range error
}
document.getElementById("result").innerHTML = err.name + "<br>" + err.message;
}
Test See‹/›

ReferenceError

When you try to reference or access a non-existent variable or object, a ReferenceError is usually thrown.

try {
var x == 5 + y; // Throw a reference error
}
document.getElementById("result").innerHTML = err.name + "<br>" + err.message;
}
Test See‹/›

SyntaxError

If there are any syntax errors in your JavaScript code, a SyntaxError will be thrown at runtime.

try {
eval("alert('Hello)");   // Missing ' will throw an error
}
document.getElementById("result").innerHTML = err.name + "<br>" + err.message;
}
Test See‹/›

TypeError

A TypeError is thrown when the value is not the expected type.

var num = 50;
try {
num.toUpperCase();   // You cannot convert a number to uppercase
}
document.getElementById("result").innerHTML = err.name + "<br>" + err.message;
}
Test See‹/›

URIError

A URIError is thrown when you specify an invalid URI (Uniform Resource Identifier).

try {
decodeURI("%");   // You cannot URI decode percent sign
}
document.getElementById("result").innerHTML = err.name + "<br>" + err.message;
}
Test See‹/›

Complete Error Reference

For a complete reference to properties and methods, please visit ourJavaScript Error Reference.

The reference section includes descriptions and examples of all Error properties and types.