M2103-TP4-Exo-3-Corrigé

 
/**
 *
 * \file    CstCodErr.h
 *
 * \authors M. Laporte, D. Mathieu
 *
 * \date    10/02/2011
 *
 * \version V1.0
 *
 * \brief   Codes d'erreurs
 *
 **/
#ifndef __CSTCODERR_H__
#define __CSTCODERR_H__

namespace nsUtil
{
    enum {KNoExc       = 0,
          KNoError     = 0,
          
          KExcDivZero  = 11,  // Division par zero

          KExcStd      = 254,
          KExcInconnue = 255 
         };

} // namespace nsUtil

#endif /* __CSTCODERR_H__ */

 
 
/**
 *
 * \file   DivisionParZero.cxx
 *
 * \author D. Mathieu
 *
 * \date   07/12/2011
 *
**/
#include <iostream>
#include <exception>
#include <iomanip>      // setw()

#include "CstCodErr.h"
#include "CException.h"

using namespace std;
using namespace nsUtil;

namespace
{
    int divisionEntiere (int num, int denom) throw (CException)
    {
        if (0 == denom) 
            throw CException ("Division par zero", KExcDivZero);
        return num / denom;

    } // divisionEntiere()
                                
    void divisionParZero ()
    {
        int lesNums   []               = { 12,  3, -5,  0, 40 };

        const unsigned KSzFractions = 
            sizeof (lesNums) / sizeof (lesNums [0]);

        int lesDenoms [KSzFractions] = {  4,  0, -5, 10,  4 };

        for (unsigned i = 0; i < KSzFractions; ++i)
        {
            cout << setw (4) << lesNums [i]   << " / "
                 << setw (4) << lesDenoms [i] << " = "; 
            try 
            {
                cout << divisionEntiere (lesNums [i], lesDenoms [i])
                     << '\n';
            }
            catch (const CException & e)
            {
                cout << "Erreur : " << e.getLibelle() 
                     << "; Code d'erreur = " << e.getCodErr() << '\n';
            }
        }

    } // divisionParZero()

} // namespace

int main ()
{
    try
    {
        divisionParZero();

        return KNoExc;
    }
    catch (const CException & e)
    {
        cerr << "Erreur        : " << e.getLibelle() << '\n' 
             << "Code d'erreur = " << e.getCodErr() << '\n';
        return e.getCodErr();
    }    
    catch (const exception & e)
    {
        cerr << "Exception standard : " << e.what() << '\n'; 
        return KExcStd;
    }    
    catch (...)
    {
        cerr << "Exception inconnue\n";
        return KExcInconnue;
    }    

} // main()