Two friends had a disagreement about the placement of the return in the following code:

var abc;
try{
     //there can possibly be 1 or more answers;
     abc = getAnAnswerFromPossibleAnswers("type","key");
     
} catch(ex){
   ex.printStackTrace();
}
//We only want the first answer even if there were more
return abc[0];

One person says the return should go inside the try because otherwise during runtime a null pointer exception (NPE) can be thrown. The other says they tested and never got an NPE - even if the value didn't exist, abc[0] returned an empty object (the test showed it returning empty curly braces).

Must the return go inside the try or is it ok to be outside as in the above snippet?

Recommended Answers

All 2 Replies

For this issue, both is applicable! But if you want to get optimum performance in your JavaScript program's, then you should try THIS LINK.

It's not OK, the return statement must go inside the catch block even when the function's contract is such that it *never* returns `null' for any input [as is the case with getElementsByTagName].

In languages which support Exceptions, there are usually two ways to break the execution flow of a function [ignoring the jmp variants offered by languages like C];
- A `return' statement is used to return from the function
- An exception is encountered and no appropriate exception handler exist in the given function.

> The other says they tested and never got an NPE - even if the
> value didn't exist, abc[0] returned an empty object (the test
> showed it returning empty curly braces)

There is a difference between `abc' being `null' and `abc' being empty. In the latter case, an undefined would be returned without the function throwing any kind of exception.

A variation of this scenario would be when there already exists a global non-empty array named `abc' in which case the return would always succeed. A sample:

<html>
  <head></head>
  <body>
    <script type="text/javascript">
    abc = [1,2,3]
    function doWithGlobal(obj) {
      try {
        var a = obj.b;
      } catch(e) {
        //do nothing
      }
      return abc[0];
    }
    function doWithoutGlobal(obj) {
      try {
        var a = obj.b;
      } catch(e) {
        //do nothing
      }
      return a[0];  //Error, since operation attempted on `undefined'
    }
    alert(doWithGlobal(""));
    alert(doWithGlobal(null));
    alert(doWithoutGlobal("")); //Error
    alert(doWithoutGlobal(null)); //Error
    </script>
  </body>
</html>

BTW, AFAIK, ECMA Error objects don't have a 'printStackTrace' property...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.