Reputation: 738
I am confused about the Javascript exception handling I wanted to clear which error can Javascript catch or which can only be handling with if elses like in case below in first case I end up into catch block because of undefined variable but in other case I stayed in the try block(and would have to use if else for catching that) inspiteof both are "not defined"
first:
try {
var x = 90;
var value = x / y;
}
catch (err) {
document.write(err.name + ": " + err.message + "<br/>");
}
second :
function add(x, y) {
var resultString = "Hello! The result of your math is: ";
var result = x + y;
// return resultString + result; not returning anything; hence, "undefined" also
}
try {
var addResult = add(2, 3);
document.write(" the result is : " + addResult + "<br/>");
} catch (err) {
document.write(err.name + ": " + err.message + "<br/>");
}
Why I am not ending up in to catch block in second case also?
Please clear my understanding.
Upvotes: 0
Views: 85
Reputation: 11352
Because there aren't any errors in the second example. The only issue is that addResult
doesn't return anything, which leads to the undefined
value. However, this is not an error.
Your first example catches an exception just because the y
variable wasn't event declared (it doesn't even has the undefined
value).
You can see this in action here:
<script type="text/javascript">
//Error
try{
alert(x);
}catch(e){
alert(e.name + ': ' + e.message);
}
//Ok
try{
var x;
alert(x);
}catch(e){
alert(e.name + ': ' + e.message);
}
</script>
Upvotes: 1
Reputation: 12774
In the first case you have not defined y anywhere so that throws an exception which is been caught by the catch block, But in the second case you have defined addResult=undefined
and you are just displaying the value, so there is no exception
If your first case was
try {
var x = 90;
var y = undefined;
var value = x / y;
}
catch (err) {
document.write(err.name + ": " + err.message + "<br/>");
}
Then there would have been no exception in first case also.
Hope you got it :)
Upvotes: 1