Home » JavaScript » JavaScript Try Catch Exception Example

About Era Balliu

Era Balliu
Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.

JavaScript Try Catch Exception Example

An important issue to solve, for those of you who use JavaScript as their programming language of choice, is handling errors. They are inevitable and unpredictable and can happen anytime, so this is out of your control (or anyone else’s control, for that matter), but what you CAN choose is how you handle them. Below, we will show you how exactly you can do that.

Types of errors

Before we start getting into details, we have to explain the possible scenarios that may happen. First, errors are divided into two groups: syntax errors and exceptions.

Syntax errors are errors made when the programmer accidentally forgets to write a piece of code (which usually are missing closed parentheses or brackets), while exceptions are errors encountered during runtime, due to illegal operations during execution. Examples of these can be undefined functions, undeclared variables and similar things, which may be correct in syntax, but problematic in execution.

JavaScript Interview Coming Up?

Subscribe to our newsletter and download the Ultimate JavaScript interview questions and answers collection right now!

In order to get you prepared for your next JavaScript interview, we have compiled a huge list of relevant questions and their respective answers. Besides studying them online you may download the eBook in PDF format!

 

Ways of using the try method

The most efficient and widespread method to deal with errors in JavaScript is the try method. It can be used in three ways:

  • try...catch
  • try...finally
  • try...catch...finally

try…catch

try... catch is the easiest way of using try methods. The try clause contains the code that we will try to execute. However, if the method encounters an exception, the execution will stop right then and there, and the exceptions will be suppressed, taking the control right after the try block, at the catch clause. Let’s give a look at the example below:

try{
    randomf(x);
    alert('this is an error ')
}
catch(e){
    alert('x is an undeclared variable')
}

We suppose that x is an undeclared variable, so the try statement has encountered an exception, so the execution will continue at catch. So the results of the piece of code above would be the suppresion of the error.

Let’s start explaining another important clause that we need in order to fully understand try methods. This would be throw.

throw

The throw statement is used inside a try... catch statement, and it throws an exception defined by you. The code after throw won’t be executed, and control will be directly transferred to the nearest catch statement. Take a look at the code snippet below:

function usernamelengthcheck(){
    try{
        var namelength=prompt("Enter username length:")
        if (isNaN(parseInt(namelength)))
            throw new Error("Please enter a username")
        else if (namelength<13)
            throw new Error("Please eneter a longer username.")
    }
    catch(e){
        alert(e.name+" "+e.message)
    }
}

As you can see, we have used try... catch and throw inside of it, using a very practical example: checking username length. We have used the throw statement inside a try block that includes an if-else loop, providing us with the possibility of throwing different exceptions for different conditions. After try encounters the exception, the control is passed to catch, and an alert is triggered, because that is what we’ve written in that block.

You might have noticed the e.name and e.message in the alert we’ve made pop up. Those two are the properties of the error object e.

try…finally

The finally clause executes whether or not there is an exception thrown. It contains statements to use after the try and catch are executed. One practical use of them is to close a file you have opened when the try block encounters and exception, and you would have to write it like this:

openFile()
try {
    workOnTheFile(newData);
}
finally {
    closeFile();
}

Usually the finally clause is used together with try and catch. We will show you how in the next section.

try… catch…finally

Previously we mentioned that the try block could be followed by catch and finally, and also by both at the same time. So how will the method work? Take a look at the code below:

try{
    for (var i=0; i<10; i++){
        if (i==7)
            break
        x=i
    }
}
catch(e) {
    e.message="I just caught an exception!!";
    alert(message);
}
finally{
    alert(i)
}

Here we have put inside try a for loop counting from 0 to 9, which breaks when i=7. It gives out an alert as soon as it catches the exception, and still the finally is executed.

Nested try blocks

You can nest a try block into another try block, into a catch block or into a finally block. The code snippet below shows an example of a try... catch... finally nested inside the catch block, but you would nest it the same inside the other blocks:

try {
    throw new Error("error thrown");
}
catch (ex) {
    try{
        throw ex;
    }
    catch (ex){
        console.log("second error thrown is now caught");
    }
    finally{
        console.log("finally caught!");
    }
}

You see that in the outer try block we have thrown an exception. Then, inside the catch block, we insert the whole try... catch... finally block. In the inner try block we have re-thrown the same exception, we have displayed a message and caught the exception in the catch block, and displayed another message in the finally block.

Here we have to keep in mind that an exception that has been thrown will be caught by the nearest catch block, and has to be re-thrown in order to be caught again.

The output to the code above will be:

//second error is now caught
//error thrown
//finally caught
//error thrown

Using try/catch blocks in real life

Take a look at the code below:

<!DOCTYPE html>
<html>
<head>
    <title>Guessing game!</title>
</head>
<body>

<p>Guess my username length to win a prize!</p>

<button type="button" onclick="usernamelengthcheck()">Trigger prompt</button>
<p id="message"></p>

<script>
    function usernamelengthcheck(){
        try{
            var namelength=prompt("Enter username length:")
            if (isNaN(parseInt(namelength)))
                throw new Error("Input should be a number")
            else if (namelength>3)
                throw new Error("Please enter another username length.")
        }
        catch(e){
            alert(e.name+" "+e.message)
        }
    }
</script>

</body>
</html>

Using the code, we have asked the user to guess the length of a username provided before and we throw errors based on the answer we get from the prompt. This code can be used in password recovery processes.

Download the source code

This was an example of try/catch in JavaScript.

Download
You can download the full source code of this example here: TryCatch

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook

 

and many more ....

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Want to take your WEB dev skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • PHP Programming Cookbook
  • jQuery Programming Cookbook
  • Bootstrap Programming Cookbook
  • Building WEB Apps with Node.js
  • CSS Programming Cookbook
  • HTML5 Programming Cookbook
  • AngularJS Programming Cookbook