0

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.

0

2 Answers 2

1

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 :)

Sign up to request clarification or add additional context in comments.

3 Comments

so in the second case I am initializing the addResult with "undefined" which is considered as initial value. and in the first I am not even initializing y with "undefined"
@staticvoidmain even var y; makes y a valid variable with the undefined value that can be used in expressions.
@staticvoidmain Jan is right, no need to define it as undefined, just need to define it.
1

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.