Browse DevX
Sign up for e-mail newsletters from DevX

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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;

     while (true) //infinitely
       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.



Thanks for your registration, follow us on our social networks to keep up-to-date