C++ newbie question--basic error handling using try, throw, catch -


i'm trying understand error handling in c++.

i have read using try, throw, catch better style , less complicated using if statements return values. i'm not sure understand how try, throw, catch works. made simple example below , great feedback problems or bad style. goal make function out of example checks results of calculation.

here questions have try, throw, catch: (1) should catch statement included in function? or should somewhere else, in main() or in function initial calculation done?

(2) overkill use try, catch, throw simple (i improve style)?

(3) if there error, terminate program. how that? or "catch" mean that done automatically?

(4) don't understand use of cerr. why not use cout? have used cerr correctly here? should have used in if/else statements?

thanks lot help.

here's example made:

double calculated = 10.2; // previous calculation double tolerance = 0.3; // can set in function double valuewanted = 10.0; // previous calculation  const int calcerror = 5; // picked number randomly use indicating error  try {    if (fabs(ftargetvalue - fcalculated) <= ftolerance)      cout << "result within range.";     else      cout << "failed.";      throw calcerror; }  catch (const int calcerror) {    cerr << "the calculation failed.\n" << endl; } 

well that's lot of questions. try give hints :

(1) not include try-catch in function. throwing exception done tell outer world happened. if can handle problem in function, not throw @ ^^ error handling catch error asap (in caller) or in general purpose handler far away in main, handle gracefully unhandled errors.

(2) rule of thumb, use exception ... exceptional things. errors candidate exceptional things. exception thrown things overflow or division 0 in math library. have decide, in general handle errors exceptions.

(3) catch not mean program end. in fact contrary. catching exception, handle problem ^^ if want terminate, simple way in simple program not catch exception, default behavior uncaught exception program termination ^^ instead, can explicitly terminate program in catch block.

(4) cerr cout, different file descriptor. means external programs can differentiate cerr cout. used error, that's not important external programs.

my2c


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -