babx pox
babx pox

Reputation: 41

Catch exception not raised

Hey guys i wrote a code to raise exception ..The code is

<html>
<body>
<script>
var d =1;
try {
  if(d == 2)  {
  console.log('fd');
}

} catch(e) {
 console.log('catch');
}

</script>
</body>
</html>

When i give the value 2 for d the code inside try works but when the value is given 1 the code inside catch didnt works..

Can you tel me why its not working ??..Any help would be great ...Thanx

Upvotes: 0

Views: 125

Answers (4)

James Donnelly
James Donnelly

Reputation: 128771

try...catch is for catching errors, not for handling conditional statements. if (d == 2) is perfectly valid and doesn't throw any errors, nor does the code within your conditional statement.

A catch clause contain statements that specify what to do if an exception is thrown in the try block. That is, you want the try block to succeed, and if it does not succeed, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch clause. If no exception is thrown in the try block, the catch clause is skipped.

MDN's Notes on try...catch

If you want to do something if d isn't equal to 2, you can use else:

if (d == 2) {
    ...
}
else {
    ...
}

If you really want to use a try...catch statement here then you're going to have to throw an error. You can do this with JavaScript's throw statement:

try {
    if (d != 2) {
        throw "d is not equal to 2!";
    }
}
catch (e) {
    ...
}

The catch block here will catch the error, and the e argument will be equal to our error string: "d is not equal to 2!".

Upvotes: 3

Akshat G
Akshat G

Reputation: 214

You need to throws the exception. Use throw "Exception" inside code like this:

try {
  if(d == 2)  {
console.log('fd');
}else{
throw "Exception";
}
} catch(e) {
 console.log('catch');
}

Upvotes: 0

skypjack
skypjack

Reputation: 50540

That's not the way a catch is intended to be used. The catch block will be visited once an exception is thrown. As an example, try to add the following else block to your if:

else { throw new Error; }

That said, it is not a good idea to control your flow by means of exceptions and I strongly discourage the use of such a solution in a production environment.

Upvotes: 1

Shilly
Shilly

Reputation: 8589

try/catch is for handling errors. You're not generating an error, since your comparison is a valid comparison. An error is not the same as an if statement that returns false.

Upvotes: 2

Related Questions