JavaScript Errors - throw, try and catch


tryThe statement tests a code block for errors.

catchThe statement handles errors.

throwThe statement creates custom errors.

finallyThe statement executes after the try and catch statements, regardless of whether an exception was triggered.


JavaScript Errors

When the JavaScript engine executes JavaScript code, various errors can occur.

They may be syntax errors, usually coding errors or typos made by programmers.

They may be spelling errors or missing features of the language (possibly due to browser differences).

They may be errors caused by incorrect output from the server or the user.

Of course, they may also be due to many other unpredictable factors.


JavaScript Throwing Errors (throw)

When an error occurs, when something goes wrong, the JavaScript engine usually stops and generates an error message.

The technical term for this situation is: JavaScript willthrowan error.


JavaScript try and catch

tryThe statement allows us to define a block of code that is tested for errors during execution.

catchThe statement allows us to define a block of code to be executed when an error occurs in the try block.

JavaScript statementstryandcatchcome in pairs.

Syntax

try { ... //Throwing an exception } catch(e) { ... //Catching and handling an exception } finally { ... //Finalization }

Example

In the following example, we deliberately wrote a typo in the code of the try block.

The catch block will catch the error in the try block and execute code to handle it.

Example

var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="This page has an error.\n\n"; txt+="Error description:" + err.message + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); } }

Try it Yourself »

The finally Statement

The finally statement executes the code block regardless of whether an exception occurred in the preceding try and catch.

Example

function myFunction() { //Get element const messageElement = document.getElementById("p01"); const inputElement = document.getElementById("demo"); //Clear previous message messageElement.innerHTML = ""; //Get input value and trim whitespace const rawValue = inputElement.value.trim(); try { //1. Check if empty if (rawValue === "") { throw new Error("Input cannot be empty. Please fill in a number."); } //2. Check if it is a valid number if (isNaN(rawValue)) { throw new Error("Please enter a valid number (e.g., 5, 10.5, -3)"); } //Convert to number const x = Number(rawValue); //3. Check if it is an integer (adjustable as needed) if (!Number.isInteger(x)) { throw new Error("Please enter an integer (decimals are not supported)"); } //4. Check the number range (adjustable as needed) if (x > 10) { throw new Error(`Number ${x}is too large, please enter5-10a number between`); } if (x < 5) { throw new Error(`Number ${x}is too small, please enter5-10a number between`); } //5. Check the special case of negative numbers if (x < 0) { throw new Error("Please enter a positive number (negative numbers are not supported)"); } //All validation passed messageElement.innerHTML= `Validation passed! The number you entered is: ${x}`; messageElement.style.color = "green"; //Other operations can be executed on success console.log(`User entered a valid number: ${x}`); } catch (err) { //Display error message messageElement.innerHTML= `Error: ${err.message}`; messageElement.style.color = "red"; //Optional: Log the error to the console console.error("Input validation failed:", err.message); } finally { //Regardless of success or failure, clear the input field inputElement.value = ""; //Optional: Refocus on the input field to make it easier for the user to re-enter inputElement.focus(); } }

Try it Yourself »


The Throw Statement

The throw statement allows us to create custom errors.

The correct technical term is: create orthrow an exception(exception)。

If you use throw together with try and catch, you can control the program flow and generate custom error messages.

Syntax

throw exception

The exception can be a JavaScript string, number, boolean, or object.

Example

This example checks the value of an input variable. If the value is wrong, an exception (error) is thrown. catch will catch this error and display a custom error message:

Example

function myFunction() { var message, x; message = document.getElementById("message"); message.innerHTML = ""; x = document.getElementById("demo").value; try { if(x == "") throw "Value is empty"; if(isNaN(x)) throw "Not a number"; x = Number(x); if(x < 5) throw "Too small"; if(x > 10) throw "Too large"; } catch(err) { message.innerHTML = "Error:" + err; } }

Try it Yourself »

Note that if the getElementById function fails, the example above will also throw an error.

Other extensions