exception - C++ how to deal with error appeared deep in objects composition? -
here each new method call must checked against error , ... slow @ least. thinking exceptions, read not handling errors. instance if throw exception, must handle previous method on stack, because otherwise there can local variable pointing allocated space in method, can't skip it. there approach?
class { int method() { ...; return 1; } }; class b { a; int method() { int err = a.method(); if (err == 1) { ...; return ret; } } }; class c { b b; int method() { int err = b.method(); if (err == 1) { ...; return ret; } } }; int main() { c c; int err = c.method(); if (err == 1) {} return 0; }
i can think of following methods deal errors deep in functions -- whether arise out of object composition or layers of functions not relevant.
method 1: throw exceptions deep in low level functions.
struct my_error_a {}; class { void method() { if ( ... ) { throw my_error_a(); } ...; } }; struct my_error_b {}; class b { a; void method() { a.method(); ...; if ( ... ) { throw my_error_b(); } } }; struct my_error_c {}; class c { b b; void method() { b.method(); ...; if ( ... ) { throw my_error_c(); } } }; int main() { c c; try { c.method(); } catch (my_error_a err) { // deal errors a. } catch (my_error_b err) { // deal errors b. } catch (my_error_c err) { // deal errors c. } catch (...) { // deal othe exceptions. } return 0; } method 2: use global error code holder keep track of errors.
int globalerrorcode = 0; class { void method() { a.method(); ...; if ( ... ) { globalerrorcode = a::errorcode; } } static int errorcode; }; class b { a; void method() { a.method(); if ( globalerrorcode != 0 ) { return; } ...; if ( ... ) { globalerrorcode = b::error_code; return; } ...; } static int errorcode; }; class c { b b; void method() { b.method(); if ( globalerrorcode != 0 ) { return; } ...; if ( ... ) { globalerrorcode = c::error_code; return; } ...; } static int errorcode; }; int main() { c c; c.method(); if ( globalerrorcode != 0 ) { // deal error code. } return 0; } method 3: return error codes @ every level , deal them @ every level.
class { int method() { if ( ... ) { return a::errorcode; } ...; } static int errorcode; }; class b { a; int method() { int err = a.method(); if ( err != 0 ) { return err; } ...; if ( ... ) { return b::errorcode; } } static int errorcode; }; class c { b b; int method() { int err = b.method(); if ( err != 0 ) { return err; } ...; if ( ... ) { return c::errorcode; } } static int errorcode; }; int main() { c c; int err = c.method(); if ( err != 0 ) { // deal errors } return 0; }
Comments
Post a Comment