This time I don't have any problem but just for curiosity I want to know how many exception are there in JavaScript.
For example I am using following code:
<script type="text/javascript">
var x;
try{
x = 1 / 0;
alert(x); // output: Infinity. FYI: JavaScript has Infinity property and it's value is 1.7976931348623157E+10308
alert(funCreate());
}
catch(obj)
{
alert(obj.fileName);
alert(obj.lineNumber);
alert(obj.message); // output: funCreate is not defined
alert(obj.name); // output: ReferenceError
alert(obj.stack);
};
</script>
here, ReferenceError is like an exception type. So if it is treated as an exception type, then can we handle the exception by type? like we all do in other programming language. see link.
Thanks...
I believe there are six exception types in JS:
EvalError
(errors produced from an eval()
; RangeError
(produced when using a number that is out of the range for where it is being used -- I've actually never seen this one in real life and I can't seem to produce it now);ReferenceError
(produced when trying to access a non-existent member of an object by name);SyntaxError
;TypeError
(when a method was expecting a value of a different type); and URIError
(produced when trying to create or decode a URI). The problem, unfortunately, is that these exception types are not supported universally -- the two big hold-outs being Safari and Opera. As well, you'll find that lineNumber
and fileName
work only on Firefox (maybe others?) and the strings you get back for message
will vary from browser to browser. So in practice, it's best to avoid using these at all and manage your exception handling manually and more directly.
There's no such syntax in javascript, but you can implement similar thing easily:
var x;
try{
x = 1 / 0;
alert(x); // output: Infinity. FYI: JavaScript has Infinity property and it's value is 1.7976931348623157E+10308
alert(funCreate());
}
catch(obj)
{
switch(obj.name) {
case 'ReferenceError':
alert(obj.fileName);
alert(obj.lineNumber);
alert(obj.message); // output: funCreate is not defined
alert(obj.name); // output: ReferenceError
alert(obj.stack);
break;
case 'AnotherError':
//do other things
break;
default:
//other stuff
}
};
You can throw anything in JavaScript, so there is no list of possible exceptions. If you would like to see all properties of the default exception object, i would recommend firebug's console.log()
-command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With