Correct Exceptions in C++ -
i learning how handle errors in c++ code. wrote example looks text file called file, , if not found throw exception.
#include <iostream> #include <fstream> using namespace std; int main() { int array[90]; try { ifstream file; file.open("somefile.txt"); if(!file.good()) throw 56; } catch(int e) { cout<<"error number "<<e<<endl; } return 0; }
now have 2 questions. first know if using exceptions correctly. second, (assuming first true) benefit using them vs if else statement?
"correctly" value judgment, (unlike other classes) there's major benefit exceptions classes being monolithic hierarchy, i'd advise throwing derived std::exception
, not int.
second, it's open question whether incorrect file name sufficiently unexpected qualify reason throw exception @ all.
as benefits vs. if/else statement: there couple. first, exceptions let segregate code deals errors, main idea , readability of code don't lost in maze of error handling. second, when have several layers of code between throwing , catching exception, code throws exception may not know how should handled. code, example, uses std::cout
report problem -- such code report errors on std::cerr
instead. can change 1 other without change code tried open file (which might deep in library, , have no clue of should used application -- , might used in application both wrong, , messagebox
preferred).
Comments
Post a Comment