C++ Kurs

Wenn fertig, bitte Fenster schließen

Lösung zur Lektion "Standard-Exceptions"


// Lösung zu Exceptions

#include <iostream>
#include <stdexcept>

using std::cout;
using std::endl;

// Globale Konstante für max. Parameterwert des Any ctors
const int ULIMIT=5;

// Klasse löst im ctor eine out_of_range Exception aus
class Any
{
  public:
    Any(int param)
    {
        if ((param<0) || (param>=ULIMIT))
            throw std::out_of_range("ctor-Parameter <0 oder >=5 !");
        cout << "ctor Any\n";
    };
    virtual ~Any()
    { cout << "dtor Any\n"; };
    void Print()
    { cout << "Any Print()\n"; }
};

// Klasse löst in Compute eine underflow_error oder overflow_error Exception aus
// wenn Ergebnis der Addition ausserhalb des short Wertebereichs liegt
class Another
{
  public:
    Another()
    { cout << "ctor Another\n"; };
    virtual ~Another()
    { cout << "dtor Another\n"; };
    short Compute(short op1, short op2)
    {
        short res = op1 + op2;
        if ((op1<0) && (op2<0) && (res>0))
            throw std::underflow_error("Underflow in Another::Compute()");
        if ((op1>0) && (op2>0) && (res<0))
            throw std::overflow_error("Overflow in Another::Compute()");
        return res;
    }
};

// main() Funktion
int main()
{
    // 5 Any Objekte nacheinander anlegen und wieder löschen
    Any *pAny;
    for (int i=0; i<=ULIMIT; i++)
    {
        // Versucht Any Objekt anzulegen
        // Max. ctor Parameterwert muss kleiner ULIMIT sein
        try
        {
            pAny = new Any(i);
        }
        catch(const std::out_of_range& ex)
        {
            cout << ex.what() << endl;
            pAny = NULL;
        }
        // Typ des derefenzierten pAny Zeigers bestimmen
        try
        {
            cout << "Type of Any: " << typeid(*pAny).name() << endl;
        }
        catch (const std::bad_typeid& ex)
        {
            cout << ex.what() << endl;
        }
        // Any Objekt wieder löschen
        delete pAny;
    }

    // Neues Any Objekt in Another Objekt konvertieren
    try
    {
        pAny = new Any(4);
        Another& ref = dynamic_cast<Another&>(*pAny);
        ref.Compute(10,10);
    }
    catch (const std::bad_cast& ex)
    {
        cout << ex.what() << endl;
    }
    // Any Objekt wieder löschen
    delete pAny;

    // Another Objekt definieren und verschiedene Additionen durchführen
    Another obj;
    try
    {
        cout << "Addition: " << obj.Compute(20000,10000) << endl;
        cout << "Addititon " << obj.Compute(-20000, 30000) << endl;
        cout << "Addititon " << obj.Compute(20000, 30000) << endl;
    }
    catch (const std::overflow_error& ex)
    {
        cout << ex.what() << endl;
    }
    catch (const std::underflow_error& ex)
    {
        cout << ex.what() << endl;
    }    
}