Gestione delle Eccezioni
Dichiarare un gestore delle eccezioni
Questo è un modo potente di gestire ogni tipo di errore che può
accadere in un programma in modo semplice ed elegante. Basta dichiarare una o
più eccezioni in una classe usando la keyword class
in
questo modo:
class exception_name {};
Poi se decidi di lanciare una eccezione usa la keyword throw
:
throw exception_name();
In C++, si può tentare (try
) di eseguire un pezzo di codice,
e catturare (catch
) ciascuna eccezione che può capitare
durante l'esecuzione:
try
{
// codice
}
catch (class_name::exception_1)
{
// gestione dell'eccezione
}
Esempio
// Esempio di una classe Vettore con gestione delle eccezioni
#include <sys/types.h>
#include <iostream.h>
#include <stdlib.h>
class Vector
{
private:
size_t si;
int *value;
public:
class BadIndex {};
class BadSize {};
class BadAllocation {};
Vector (size_t);
int& operator[](size_t);
};
Vector::Vector (size_t s)
{
if (s <= 0) throw BadSize();
si = s;
value = new int[si];
if (value == 0) throw BadAllocation();
}
int& Vector::operator[] (size_t i)
{
if ((i < 0) || (i >= si)) throw BadIndex();
return value[i];
}
int main (int, char **)
{
Vector *v;
try
{
int si, index;
cout << "Give the size of the array: ";
cin >> si;
v = new Vector (si);
cout << "Give an index in the array: ";
cin >> index;
cout << "Give its value: ";
cin >> (*v)[index];
}
catch (Vector::BadSize)
{
cerr << "The size of an array must be greater than 0.\n";
exit(1);
}
catch (Vector::BadAllocation)
{
cerr << "Memory allocation error.\n";
exit(2);
}
catch (Vector::BadIndex)
{
cerr << "Index out of range.\n";
exit(3);
}
//...
exit(0);
}