how to handle an exception? for example suppose i am running my script one of friend has send me message in YahooMessenger or any other pop-up window then i have to close that window and start running my script from where it has got stopped.
There is a bigger problem than just trying to figure out how to handle an unexpected pop up......The basic core situation you are running your tests.
You should be focusing on the test at hand, and ensuring the application is performing as expected, and not having to code for situations that fall outside of the application. Are you going to code for every type of IM popup? Every new email notification? Any other window or error other applications are goint o possibly produce?
You are treading into scripting against the environment and not the application. Granted the application is going to be running in an environment where other applications will be running, but when you are doing your automated tests usually best practices mean focusing on as little external influence from other applications as possible.
Either work to get a dedicated system for your automated test runs, or as Juleo first suggested, close out the messenger application and focus on the task at hand.