-5

I have the following class:

var a = $scope.option.userMap[userId].name;

This fails when there is no value in userMap that has a key of userId. The error message comes up when it tries to do the .name of something that's not defined.

Is there a simple way that I could catch this error? When the error happens I would like the variable a to be set to "unknown"

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

5 Answers5

5

Yes.

try {
    var a = $scope.option.userMap[userId].name;
} catch(e) {
    //catch a error
} finally {
    //execute always
}

About finally block vs return statement:

function something() {
    try {
        return $scope.option.userMap[userId].name;
    } catch(e) {
        return e.message
    } finally {
        alert('Yohoooo!')
    }
}

You will always see the alert when call the something function.

Alex
  • 11,115
  • 12
  • 51
  • 64
2

Javascript has something exactly like try / catch, but why use it when you can just check if the key exists instead :

if (userId in $scope.option.userMap) {

    var a = $scope.option.userMap[userId].name;

}else{

    var a = 'unknown';

}
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    Very good, except `a` should be set to "unknown" :) – Jongware Jan 24 '14 at 15:36
  • 1
    @Jongware - Yeah, that's probably better ;-) – adeneo Jan 24 '14 at 15:36
  • 1
    +1, by the way, for answering the Question Not Asked: [Blindly using `try-catch` or checking your code for errors](http://stackoverflow.com/questions/3217294/javascript-try-catch-performance-vs-error-checking-code) – Jongware Jan 24 '14 at 15:40
1

Of course:

try {
   // Live hard...dangerous code
} catch(e) {
   // Manage your mess
}

Optionall you can add a finally clause, that is always executed:

finally {
    // Always executed
}
bgusach
  • 14,527
  • 14
  • 51
  • 68
1

Yes, there is.

This is the syntax:

try {
    //Run some code here
} catch(err) {
    //Handle errors here
}

For more information:

http://www.w3schools.com/js/js_errors.asp

Denis C de Azevedo
  • 6,276
  • 2
  • 32
  • 49
1

Though the replies above have answered the question of whether JS has try/catch feature, they have failed to point out the fact that it is not best practice to use try/catch blocks to work around undefined variables. Better way to do this is:

var userObj = $scope.option.userMap[userId];
var a = userObj ? userObj.name : undefined;
RaviH
  • 3,544
  • 2
  • 15
  • 14