JavaScript

JavaScript Try Catch Exception Example

EDITORIAL NOTE: In this post, we feature a comprehensive JavaScript Try Catch Exception Example. The try statement lets you test a block of code for errors. The catch statement lets you handle the error.

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.

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

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button