Demonstrate exceptions using a factorial function - C++ Statement

C++ examples for Statement:try catch

Description

Demonstrate exceptions using a factorial function

Demo Code

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

int factorial(int n) throw (string){
    if (n < 0){
        throw string("Argument for factorial negative");
    }/* w  w  w .  j  a va 2s  . c  o  m*/

    int accum = 1;
    
    while(n > 0){
        accum *= n;
        n--;
    }
    return accum;
}

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

        // this will generate an exception
        cout << "Factorial of -1 is " << factorial(-1) << endl;

    }catch(string error){
        cout << "Error occurred: " << error << endl;
    }
    catch(...)
    {
        cout << "Default catch " << endl;
    }
    return 0;
}

Result


Related Tutorials