Re: Error handling?
desktop <fff@sss.com> wrote in message...
I have a class that contains:
class MyArray {
public:
MyArray(int a) : num(a){}
void generate() {
// > ip = new int[a];
ip = new int[ num ];
}
int& operator[](int Index) {
return ip[Index];
}
...
...
private:
int* ip;
int num;
};
But I assume its rather error-prone. What kind of techniques exist for
handling memory allocation and indexing errors?
std::vector<int> MyArray( 1, 42);
try{
int aaa = MyArray.at(2);
}
catch(std::out_of_range const &oor){
std::cout<<" caught = "<<oor.what()<<std::endl;
}
<G>
Eg. is it necessary to
catch a possible bad_alloc thrown by new or out_of_range etc. I would
like to know what the standard approaches towards error-safe code are in
the above example.
"necessary" depends on how much damage will be done if the memory allocation
fails inside your class. <G>
In "Thinking in C++" vol.2, Eckel/Allison have a whole chapter dedicated to
'exception handling', and show how to do it inside a class. It should give
you a good start on that. ( it may not be perfect due to changes in standard
since it was 'final'-ized. ).
Get "Thinking in C++", 2nd ed. Volume 1&2 by Bruce Eckel
(available for free here. You can buy it in hardcopy too.):
http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html
See: // : C01:InitExcept.cpp From "Thinking in C++, Vol2"
[ preview snippet, modified for ostream output ]
class Derived : public Base {
std::ostream &dout;
public:
class DerivedExcept{
char const *msg;
public:
DerivedExcept( char const *msg) : msg(msg){}
char const* what() const { return msg; }
};
Derived(int j, std::ostream &out)
try : Base(j, out), dout(out){ // Ctor body
// 'Base' just throws BaseExcept();
out<<"This won't print"<<std::endl;
}
catch( BaseExcept& ){
out<<"catch(BaseExcept&) ";
throw DerivedExcept("Base subobject threw");;
}
~Derived(){ // Dtor
dout<<"~Derived() Dtor called."<<std::endl;
}
}; // class Derived
{ using std::cout; // main or function
try{
Derived d( 3, cout );
}
catch( Derived::DerivedExcept &ddd ) {
cout<<"catch( DerivedExcept &)\n";
cout<<ddd.what()<<std::endl; // "Base subobject threw"
}
}
Or, check the book you have for something similar.
--
Bob R
POVrookie