Advertisement

Advertisement


JavaScript Error Handling

Handling Errors

There are a number of reasons that may cause errors:

  • Entering invalid value in any form field.
  • Referncing objects or functions that do not exist.
  • Mathematical operations errors.
  • A problem with network connection.

These all are runtime errors and every language should have proper measures to handle these errors. Javascript has some statements and methods which can handle these errors.

Statement Used in Error Handling

Statement Description
try The try statement contains code which can have error possibilities.
catch The catch statement handles the error.
throw The throw statement lets you create custom errors.
finally The finally statement executes the code, after try and catch, regardless of the result.

The try...catch Statement

The try-catch statement is used to check for runtime errors, and handle them. The code that might throw an error will be placed in the try block of the statement, and the code to handle the error is placed in the catch block

Syntax:

try {
    // Code that may cause an error
     } catch(error) {
    // Action to be performed when an error occurs
    }

If an error occurs at any point in the try block, code execution immediately transferred from the try block to the catch block. The catch block will be ignored if no error is detected in the try block, and the program will continue execution.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Error Handling </title>
</head>
<body>
<script>
try {
var greet = "Hi, JavaScript!";
document.write(greet);
// Trying to access a non-existent variable
document.write(welcome);
// If error occurred following line won't execute
alert("All statements are executed successfully.");
} catch(error) {
// Handle the error
alert("Caught error: " + error.message);
}
// Continue execution
document.write("<p>Hello World!</p>");
</script>
</body>
</html>

The finally Statement

The finally block will always execute, regardless of whether an error has occurred in the try block or not. In the example below, try giving a valid value once and an invalid value other time, and then check the finally statement execution.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Error Handling finally Statement </title>
</head>
<body>
<script>
// Assigning the value returned by the prompt dialog box to a variable
var num = prompt("Enter a positive integer between 0 to 100");
// Storing the time when execution start
var start = Date.now();
try {
if(num > 0 && num <= 100) {
alert(Math.pow(num, num)); // the base to the exponent power
} else {
throw new Error("An invalid value is entered!");
}
} catch(c) {
alert(c.message);
} finally {
// Displaying the time taken to execute the code
alert("Execution took: " + (Date.now() - start) + "ms");
}
</script>
</body>
</html>

Throwing Errors

By throw statement you can manually throw an error which was so far done automatically by javascript. The general syntax of the throw statement is: throw expression;

Look at the example below to understand it better.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Error Handling throw Statement </title>
</head>
<body>
<script>
var num = prompt("Please enter an integer value");
try {
if(num == "" || num == null || !Number.isInteger(+num))
{
throw new Error("Invalid value!");
} else {
document.write("Correct value!");
}
} catch(c) {
document.write(c.message);
}
</script>
</body>
</html>

Now we're going to create a function cuberoot() to find the cube root of a number. This can be done simply by using the JavaScript built-in function Math.cbrt(), but the problem here is, it returns NaN for negative numbers, without providing any hint on what has gone wrong.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Error Handling try Statement </title>
</head>
<body>
<script>
function cuberoot(number) {
// Throw error if number is negative
if(number < 0) {
throw new Error("Sorry, can't calculate cube root of a negative number.");
} else {
return Math.cbrt(number);
}
}
try {
cuberoot(125);
cuberoot(729);
cuberoot(-9);
cuberoot(1000);
// If error is thrown following line won't execute
alert("All calculations are performed successfully.");
} catch(c) {
// Handle the error
alert(c.message);
}
</script>
</body>
</html>

Tip : Theoretically it is possible to calculate the square root of negative number by using the imaginary number.But imaginary numbers are not supported in JavaScript. learning a little bit every day.









Become a Patron!

Note: If the updated content is not visible to you please refresh the cookies by pressing CTRL + Shift + R.