CPP Errors and Exceptions

Handling Errors and Exceptions?

  • The basic idea behind exceptions is fairly straightforward:
    • The computer tries to run a piece of code. This code might try to allocate resources such as memory, might try to lock a file, or any of a variety of tasks.
    • Logic (code) is included to be prepared in case the code you are trying to execute fails for some exceptional reason.
    • In case your code is being used by other code (for instance, one function calling another), you also need a mechanism to pass information about any problems (exceptions) from your level, up to the next.
    try {
       SomeDangerousFunction();
    }
    catch(OutOfMemory){
       // take some actions
    }
    catch(FileNotFound) {
       // take other action
    }
    catch (...) {              // this refer to any other exception
    }
  • You can create your own exceptions, and gain the ability to have customized handlers (catch blocks) for exceptions that are meaningful to your application.
  • To create an exception that causes the try statement to react, the keyword, throw, is used.
    throw exception;
  • The value that you throw in the exception can be of virtually any type.
    Example that throw a character string:
    #include <iostream>
    
    using namespace std;
    
    int main() {
      int speed = 90;  // speed : meter/second
      int time = -10;    // second
    
      try   {
        cout << "Speed multiply by time (meter) = ";
        if ( time < 0 ) {
          cout << "(" << speed << "*" << time <<")?" << endl;
          throw "Time must be creater or equal to 0!";
        }
        else
          cout << (speed *time) << endl;
      }
      // as character string is thrown the try 
      // will use this catch 
      catch( const char * ex ) {
        cout << "\nError: " << ex  << endl;
      }
      catch(...) {
        cout << "Something else has gone wrong!" << endl;
      }
      return 0;
    }
    When we run this application, the result will be:
    Speed multiply by time (meter) = (90*-10)?
    
    Error: Time must be creater or equal to 0!

    You can download this example here (needed tools can be found in the right menu on this page).

  • You can create much more complex classes for throwing an exception.
  • You can use all you have learned to build a such class, including inheritance and Polymorphism with virtual methods.
    Example that throw class exception:
    #include <iostream>
    #include <sstream>
    #include <string>
    using namespace std;
    // Define the exception classes
    
    class Exception {
    protected:
      string * errors;
      int errorSize;
    
    public:
      Exception() :errorSize(0) {
        errors = new string[10];
        errors[errorSize] ="You got runtime error(s):\n";
        errorSize++;
      }
      virtual ~Exception(){
        delete [] errors;
      }
      void showErrors()  {
        for (int i=0 ; i< errorSize ; i++ ) {
          cout << errors[i];
        }
      }
    
    };
    
    class VectorException : public Exception {
    protected:
      int size;
    public:
      VectorException(int size):size(size) {}
      VectorException (const VectorException & refObject){
        size=refObject.size;
        for (int i=0 ; i< refObject.errorSize ; i++ ) {
          errors[i]=refObject.errors[i];
        }
        errorSize=refObject.errorSize;
      }
      void ValidateInitialSize() {
        errorSize=1;
        if (size == 0) {
          ostringstream oss;
          oss << "The vector cannot be : " << size << "\n";
          errors[errorSize]=oss.str();
          errorSize++;
        }
        if (size > 5000) {
          ostringstream oss;
          oss << "The vector is too large : " << size << "\n";
          errors[errorSize]=oss.str();
          errorSize++;
        }
        if (size < 0) {
          ostringstream oss;
          oss << "The vector cannot be less than zero : " << size << "\n";
          errors[errorSize]=oss.str();
          errorSize++;
        }
        if (size <=20) {
          ostringstream oss;
          oss << "The vector must be greater then 20 : " << size << "\n";
          errors[errorSize]=oss.str();
          errorSize++;
        }
        if (errorSize>1) {
          throw VectorException(*this);
        }
      }
    
      void ValidateBoundary(int offSet) {
        errorSize=1;
        if (offSet < 0 || offSet >= size) {
          ostringstream oss;
          oss << "The index is out of Boundary : " << offSet << "\n";
          errors[errorSize]=oss.str();
          errorSize++;
          throw VectorException(*this);
        }
      }
    };
    
    class Vector : private VectorException {
    public:
      // Constructors
      Vector(int size = 5);
      ~Vector() { delete [] pType;}
    
      // overloaded operators
      Vector& operator=(const Vector&);
      int& operator[](int offSet);
      // Accessors
      int getSize() const { return size; }
    private:
      int *pType;
      int  size;
    };
    
    Vector::Vector(int size): size(size), VectorException(size) {
      ValidateInitialSize();
      pType = new int[size];
      for (int i = 0; i < size; i++)
        pType[i] = 0;
    }
    
    int & Vector::operator [] (int offSet) {
      ValidateBoundary(offSet);
      return pType[offSet];
    }
    
    
    int main() {
    
      cout << "\nTry a vector size  > 20 but less the 100\n";
      try  {
        Vector intVector(30);
        for (int j = 0; j < 100; j++) {
          intVector[j] = j;
          cout << "intVector[" << j << "] okay..." << endl;
        }
      }
      catch (VectorException & theVectorException)  {
        theVectorException.showErrors();
      }
      catch (Exception & theException) {
        theException.showErrors();
      }
      catch (...)  {
        cout << "Something went wrong!" << endl;
      }
      // End Try a vector size  > 20 but less the 100
    
      cout << "\nTry a vector size= 0\n";
      try  {
        Vector intVector(0);
        for (int j = 0; j < 100; j++) {
          intVector[j] = j;
          cout << "intVector[" << j << "] okay..." << endl;
        }
      }
      catch (VectorException & theVectorException)  {
        theVectorException.showErrors();
      }
      catch (Exception & theException) {
        theException.showErrors();
      }
      catch (...)  {
        cout << "Something went wrong!" << endl;
      }
      // End Try a vector size= 0
    
      cout << "\nTry a vector size  < 20 and >0\n";
      try  {
        Vector intVector(10);
        for (int j = 0; j < 100; j++) {
          intVector[j] = j;
          cout << "intVector[" << j << "] okay..." << endl;
        }
      }
      catch (VectorException & theVectorException)  {
        theVectorException.showErrors();
      }
      catch (Exception & theException) {
        theException.showErrors();
      }
      catch (...)  {
        cout << "Something went wrong!" << endl;
      }
      // End Try a vector size  < 20
      return 0;
    }
    When we run this application, the result will be:
    Try a vector size  > 20 but less the 100
    intVector[0] okay...
    intVector[1] okay...
    intVector[2] okay...
    intVector[3] okay...
    intVector[4] okay...
    intVector[5] okay...
    intVector[6] okay...
    intVector[7] okay...
    intVector[8] okay...
    intVector[9] okay...
    intVector[10] okay...
    intVector[11] okay...
    intVector[12] okay...
    intVector[13] okay...
    intVector[14] okay...
    intVector[15] okay...
    intVector[16] okay...
    intVector[17] okay...
    intVector[18] okay...
    intVector[19] okay...
    intVector[20] okay...
    intVector[21] okay...
    intVector[22] okay...
    intVector[23] okay...
    intVector[24] okay...
    intVector[25] okay...
    intVector[26] okay...
    intVector[27] okay...
    intVector[28] okay...
    intVector[29] okay...
    You got runtime error(s):
    The index is out of Boundary : 30
    
    Try a vector size= 0
    You got runtime error(s):
    The vector cannot be : 0
    The vector must be greater then 20 : 0
    
    Try a vector size  < 20 and >0
    You got runtime error(s):
    The vector must be greater then 20 : 10

    You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.