Exceptions in JavaScript

Exceptions in Javascript

You can't predict and check every possible condition in your code to avoid errors, Even if you are able to achieve this then also you can't guarantee of exception free output. Then it is going to be more important to handle all errors correctly and display more appropriate and related error messages to client.

As similar to other programming languages exception in javascript is being handled by try... catch statements.

<html>

<head>

<title></title>

<script type="text/javascript">

    var TryCatch = function () {

        try {

            var error = new Error("aaaaaa!");

            error.name = "SampleError";

            throw error;

        } catch (e) {

            document.writeln(e.name + ': ' + e.message);

        }

    }

    TryCatch();

</script>

</head>

<body>

</body>

</html>

 
 
But there is one dissimilarity from other languages like c# here. You can't write multiple catch blocks in javascript. Then the question arises that how will we distinguish between different types of errors. There are two ways of doing this one is by checking instanceof operator(to get more info about instanceof operator visit https://developer.mozilla.org/en/JavaScript/Reference/Operators/instanceof) on error variable(here e is the error variable in above code snipet).

<script type="text/javascript">

    var TryCatch = function () {

        try {

            throw new TypeError;

            //throw new URIError;

        } catch (e) {

            if (e instanceof TypeError)

                document.writeln('type error');

            else if (e instanceof URIError)

                document.writeln('uri error');

        }

    }

    TryCatch();

</script>

In the above code instanceof operator is actually checking that the error object contains which type of error object.

Alernatively, we can check name property of error object as in below:

<script type="text/javascript">

    var TryCatch = function () {

        try {

            //throw new TypeError;

            throw new URIError;

        } catch (e) {

            if (e.name == 'TypeError')

                document.writeln('type error');

            else if (e.name == 'URIError')

                document.writeln('uri error');

        }

    }

    TryCatch();

</script>

 
This way you can handle multiple error conditions in a single try..catch. But the question arises how many types of error constructors we have in javascript. There are actually 6 types of error constructors in javascript.

EvalError

RangeError

ReferenceError

SyntaxError

TypeError

URIError
 

Ebook Download
View all
Learn
View all