Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: All
Feb 19, 1999

Exception Handling Misuses

Exceptions can be used as an alternative control structure in addition to for-loops or while-blocks. For example, you can use exceptions to implement a simple application that prompts the user to enter data until a certain condition has been fulfilled:
 
  #include <iostream>
  using namespace std;

  class Exit{}; //used as exception object

  int main()
 {
   int num;
   cout<< "enter a number; 99 to exit" <<endl;

   try
   {
     while (true) //infinitely
     {
       cin>>num;
       if (num == 99) 
         throw Exit(); //exit the loop
       cout<< "you entered: " << num << "enter another number " <<endl;
     }
   }
   catch (Exit& )
   {
     cout<< "game over" <<endl;
   }
 }
I wouldn't recommend this style of programming, though. It is inefficient due to the performance overhead resulting from exception handling. Furthermore, it is verbose, and could have been much simpler and shorter had you written it with traditional control structures such as for- or while-statements instead. As a rule, you should limit using exceptions to severe runtime errors.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap