COMP2004
Programming Practice
2002 Summer School


Kevin Pulo
School of Information Technologies
University of Sydney


(page 1)


Exception Safety




(page 2)


When to throw




(page 3)


When to catch




(page 4)


Unexpected Exceptions




(page 5)


Simple Throw Guides




(page 6)


Simple try/catch Guides




(page 7)


RAII




(page 8)


Bad Example Code


void some_function(int size) {
char *fred = new char[size];
// do some stuff
delete [ ] fred;
}



(page 9)


Fixing with try/catch


void some_function(int size) {
char *fred = new char[size];
try {
// do some stuff
} catch (...) {
delete [ ] fred;
throw;
}
delete [ ] fred;
}


(page 10)


In General


void some_function() {
// acquire resource A
// do stuff
// acquire resource B
// do stuff
// possibly more resources...
// release resource B
// release resource A
}


(page 11)


Too Complicated




(page 12)


Fixing with local variable


void some_function(int size) {
char fred[size];
// do some stuff
}


(page 13)


Use a class/struct


struct char_array {
char *array;
char_array(int size) {
array = new char[size];
}
~char_array() {
delete [ ] array;
}
operator char*() {
return array;
}
};


(page 14)


Original now becomes


void some_function(int size) {
char_array fred(size);
// do some stuff
}



(page 15)


auto_ptr




(page 16)


auto_ptr example


void do_enrolment(string name,
string course) {
Person *pp = new Person(name);
auto_ptr p(pp);

p->enrol(course);
// do some stuff
if (error_found) throw Error();
// do some more stuff
// not needed: delete pp;
}


(page 17)


auto_ptr caveats




(page 18)


auto_ptr usage




(page 19)


Constructors and Exceptions




(page 20)


Member Initialiser Exceptions


SomeClass::SomeClass(int size)
: vec(size)
{
// Contents of constructor...
}


(page 21)


Member Initialiser Exceptions


SomeClass::SomeClass(int size)
try
: vec(size)
{
// Contents of constructor...
}
catch (Error e) {
// ...
}


(page 22)


Copy Constructors and Exceptions




(page 23)


Destructors and Exceptions





(page 24)