JavaScript Error - Throw and Try to Catch

try The statement enables you to test for errors within a code block.

catch The statement allows you to handle errors.

throw The statement allows you to create custom errors.

finally Enables you to execute code after try and catch, regardless of the outcome.

Errors will always happen!

Various errors will occur when executing JavaScript code.

Errors may be due to coding errors by programmers, errors caused by incorrect input, or due to other unforeseen issues.

Example

In this example, we use adddlert Write a warning code to intentionally create an error:

<p id="demo"></p>
<script>
try {
    adddlert("Welcome to the site!");
}
catch(err) {
    document.getElementById("demo").innerHTML = err.message;
}
</script>

Try It Yourself

JavaScript captures adddlert as an error and then executes code to handle the error.

JavaScript try and catch

try The statement allows you to define a code block to detect errors during execution.

catch The statement allows you to define a code block to be executed if an error occurs in the try code block.

JavaScript Statements try and catch Appear in pairs:

try {
     Code block for testing
}
 catch(err) {
     Code block for handling errors
} 

JavaScript throws an error

When an error occurs, JavaScript usually stops and generates an error message.

The technical term is described as follows:JavaScript will throw an exception (throw an error).

JavaScript actually creates an object with two properties Error Object:name and message.

throw statement

throw The statement allows you to create custom errors.

Technically, you canThrowing an exception (throwing an error).

Exceptions can be JavaScript strings, numbers, booleans, or objects:

throw "Too big";    // Throw text
throw 500;          // Throw a number

If you put throw with try and catch Together, they can control the flow of the program and generate custom error messages.

Input Validation Example

This example checks the input. If the value is incorrect, an exception (err) is thrown.

The exception (err) is caught by the catch statement and displays a custom error message:

<!DOCTYPE html>
<html>
<body>
<p>Enter a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
    var message, x;
    message = document.getElementById("message");
    message.innerHTML = "";
    x = document.getElementById("demo").value;
    try { 
        if(x == "") throw "Empty";
         if(isNaN(x)) throw "not a number";
         x = Number(x);
        if(x < 5) throw "Too small";
        if(x > 10) throw "Too big";
    }
    catch(err) {
        message.innerHTML = "Input is " + err;
    }
}
</script>
</body>
</html> 

Try It Yourself

HTML validation

The above code is just an example.

Modern browsers usually combine JavaScript with built-in HTML validation, using predefined validation rules defined in HTML attributes:

<input id="demo" type="number" min="5" max="10" step="1">

You will learn more about form validation in later chapters of this tutorial.

finally statement

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

try {
     // Code block for testing purposes
}
 catch(err) {
     // Code block for error handling
} 
finally {
     // Code block that is executed regardless of the result
}

Example

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

Try It Yourself

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

Property Description
name Set or return the error name
message Set or return the error message (a string)

Error Name Values

The 'name' property of error can return six different values:

Error Name Description
EvalError Error that has occurred in the eval() function
RangeError Error out of number range has occurred
ReferenceError Illegal reference has occurred
SyntaxError Syntax error has occurred
TypeError Type error has occurred
URIError Errors that have occurred in encodeURI()

Below, we will elaborate on these six different values.

Eval Error

EvalError indications of errors in the eval() function.

Newer versions of JavaScript will not throw any EvalErrorPlease use SyntaxError instead.

Range Error

RangeError will be thrown when you use a number outside the legal value range.

For example: You cannot set the number of significant digits of a number to 500.

Example

var num = 1;
try {
    num.toPrecision(500);   // A number cannot have 500 significant digits
 }
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
} 

Try It Yourself

Reference Error

If you use (reference) a variable that has not been declared, then ReferenceError will be thrown:

Example

var x;
try {
    x = y + 1;   // y cannot be referenced (used)
 }
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
} 

Try It Yourself

Syntax Error

If you calculate code with syntax errors, it will SyntaxError Thrown:

Example

try {
    eval("alert('Hello')");   // Missing ' will cause an error
}
catch(err) {
     document.getElementById("demo").innerHTML = err.name;
} 

Try It Yourself

Type Error

If the value you are using is not within the expected range, then TypeError Thrown:

Example

var num = 1;
try {
    num.toUpperCase();   // You cannot convert the number to uppercase
 }
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
} 

Try It Yourself

URI Error

If you use illegal characters in URI functions, then URIError Thrown:

Example

try {
    decodeURI("%%%");   // You cannot encode these percent signs in URI
 }
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
} 

Try It Yourself

Non-standard Error Object Properties

Mozilla and Microsoft have defined non-standard error object properties:

  • fileName (Mozilla)
  • lineNumber (Mozilla)
  • columnNumber (Mozilla)
  • stack (Mozilla)
  • description (Microsoft)
  • number (Microsoft)

Do not use these properties on public websites. They will not work in all browsers.