Exceptions in Javascript
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 the above code snippet).
- <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.
Alternatively, we can check the 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 on 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

Join the conversation! Your thoughts help the community grow.