Handling error by try & catch in different browsers

While executing Javascript code some time the script may develop some error and an un-wanted ugly message gets posted to the viewer. This message gets displayed in Tools > Error console of firefox browser and in internet explorer it get displayed through a new window. In IE it says about run time error and ask us to debug or not. As a programmer it may help us but such messages results in poor user experience. How to suppress error messages in JavaScript ? We can prevent this window displaying by handling the error and its associated message.

JavaScript has exception handling by using try catch functions. We can keep our code block inside try and pass all the error to catch block. Here is a sample code on try and catch.

Note that we have not defined the variable my_sum and try to print the value by using document.write. For your learning we have defined the variable and commented this line , you can uncomment and check the difference.
<script type="text/javascript">
<!--
try
{
//var my_sum=5;
document.write("The sum of 2 and 3 = " + my_sum);
}
catch(err)
{
document.write("There is an error Sorry");
document.write("<br>...You can continue with rest of the page...<br>");

}
//-->
</script>
We can display the error message which has caused the exception by error object. Here internet explorer and firefox behaves differently so we have to identify the browsers and then display the message accordingly through an alert box.
<script type="text/javascript">
<!--
try
{
//var my_sum=5;
document.write("The sum of 2 and 3 = " + my_sum);
}
catch(err)
{
document.write("There is an error Sorry");

if(navigator.userAgent.indexOf("Firefox")!=-1){
var msg=err;
}
else if (navigator.appName.indexOf("Internet Explorer")!=-1){
var msg=err.description;
}

alert(msg);

}
//-->
</script>

Using the throw Statement in JavaScript

The throw statement in JavaScript is used to generate custom error messages in our program. When a throw statement is encountered, it stops the execution of the code and passes control to the nearest catch block, if available, or displays the error in the console. We can throw any type of value—an error object, string, number, or other data types—to indicate that something went wrong in our code.

Syntax

throw expression;
  • Custom Error Messages: We can throw our own custom error messages when certain conditions in our code are not met.
  • Input Validation: Use throw to generate an error when user input is invalid.
  • Catch Blocks: throw can be used in conjunction with try...catch to handle errors gracefully.

Example: Throwing an Error in JavaScript

function divideNumbers(a, b) {
    if (b === 0) {
        throw "Division by zero is not allowed";
    }
    return a / b;
}

try {
    let result = divideNumbers(10, 0);
    console.log(result);
} catch (error) {
    console.log("Error: " + error);
}
  • throw "Division by zero is not allowed";: When b is 0, this custom error message is thrown.
  • try...catch block: The catch block catches the thrown error, preventing the script from crashing, and displays a meaningful error message.

Output

Error: Division by zero is not allowed

Throwing Different Types of Errors

We can throw other data types such as:

  • Strings: A simple error message as a string.
  • Numbers: Specific error codes.
  • Custom Objects: Complex error details (e.g., an error object containing additional information).
  • Built-in JavaScript Errors: We can throw predefined error types such as Error, RangeError, TypeError, etc.

Example: Throwing an Error Object

function checkAge(age) {
    if (age < 18) {
        throw new Error("You must be at least 18 years old.");
    }
    console.log("You are old enough.");
}

try {
    checkAge(16);
} catch (error) {
    console.log(error.name + ": " + error.message);
}
  • throw new Error("message"): Throws a predefined Error object with a custom message.
  • error.name: The type of error (Error).
  • error.message: The custom error message passed during the throw.

Output

Error: You must be at least 18 years old.

Common Built-in Error Types

  • Error: A generic error object.
  • TypeError: Thrown when a value is not of the expected type.
  • RangeError: Thrown when a number is out of range.
  • ReferenceError: Thrown when an invalid reference is made (e.g., using an undefined variable).
  • SyntaxError: Thrown when there is a syntax issue in our code.

Example: Throwing Different Error Types

function checkNumber(num) {
    if (typeof num !== 'number') {
        throw new TypeError("Expected a number");
    }
    if (num < 0 || num > 100) {
        throw new RangeError("Number must be between 0 and 100");
    }
    console.log("Valid number: " + num);
}

try {
    checkNumber(150);
} catch (error) {
    console.log(error.name + ": " + error.message);
}

Output

RangeError: Number must be between 0 and 100

JavaScript Basic
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com










    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer