How to get if category has posts?

You just need add if condition here, check the following code

    query_posts('cat=2');
if(have_posts()) { /*continue with while code*/  } //end of if