C++ Exception Creating a custom exception class

Description

C++ Exception Creating a custom exception class

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <sstream>
using namespace std;

class MyException{
  public:/*from   w ww .  j  a v a  2s.c o m*/
    MyException(const char* pMsg, int n,const char* pFunc,const char* pFile, int nLine): msg(pMsg), errorValue(n),funcName(pFunc), file(pFile), lineNum(nLine){}

    virtual string display()
    {
        ostringstream out;
        out << "Error <" << msg << ">" << " - value is " << errorValue << "\n" << "in function " << funcName << "()\n" << "in file " << file << " line #" << lineNum << ends;
        return out.str();
    }
  protected:
    // error message
    string msg;
    int    errorValue;

    string funcName;
    string file;
    int lineNum;
};

// factorial - compute factorial
int factorial(int n) throw(MyException)
{
    if (n < 0)
    {
        throw MyException("Negative argument not allowed",n, __func__, __FILE__, __LINE__);
    }
    int accum = 1;
    while(n > 0)
    {
        accum *= n;
        n--;
    }
    return accum;
}

int main(int nNumberofArgs, char* pszArgs[])
{
    try
    {
        // this will work
        cout << "Factorial of 3 is " << factorial(3) << endl;

        // this will generate an exception
        cout << "Factorial of -1 is " << factorial(-1) << endl;
    }catch(MyException e){
        cout << e.display() << endl;
    }
    catch(...)
    {
        cout << "Default catch " << endl;
    }
    return 0;
}



PreviousNext

Related