Monday, May 27, 2013

Handling Multiple Exceptions in Java 7

Not much introduction in this post, but as most of you know, that was how Java SE used to handle multiple exceptions:
catch (DataFormatException ex) {
     ex.printStackTrace();
     throw ex;
catch (FileNotFoundException ex) {
     ex.printStackTrace();
     throw ex;
}
Now the problem rises when you do not want to write much code specifically to each clause, maybe you just are printing the stack trace or logging the exception. With the Java SE 7, you can write less code and be more flexible, something like this:
catch (DataFormatException|FileNotFoundException ex) {
    ex.printStackTrace();
    throw ex;
}

Thursday, May 16, 2013

Match an element against an array in Javascript

There are times when you need to check whether an element is inside an array. You might want to loop thorough the whole array and check one-by-one whether the element belongs to an array or not:
var element = "one";
var array = ["one", "two", "three"];

for (var i= 0; i < array.length; i++)
{
   if (element === array[i])
   {
      alert("element exists in array");
   }
}
This approach is not optimized. First, it will produce additional lines of unnecessary code and therefore makes the code look ugly. Second, looping through element of an array is costly, especially when the array has two many elements. A more optimized way of handling this case is with use of Regular Expressions. Without further a due, let us look at the code:
if ((new RegExp('\\b' + array.join('\\b|\\b') + '\\b') ).test(element))
{
   alert("element exists in array");
}
In this approach, we create a new regular expression by joining elements of array into an string and match it against the element with test() method. Just to remark, \b matches the empty string at the beginning or end of a word.