4 ms·
Return an error or fatally exit the program, depending.
by gilbetron 4y ago
Return an error or fatally exit the program, depending.
- grishka 4y agoIf you return an error, it needs to be checked for in every place where this function is called. Yes, I know C libraries and OS APIs do this often, but that's C, it's the only thing it can do. This just invites human error. Besides, it's often desirable to handle multiple different error conditions (arising from different steps as you process the input data) in one place, which is complicated with this approach. Java-like exception handling makes it easy to handle all errors in a single place and be sure none go unnoticed. This is especially useful when you're accepting external input (a file, a network packet/stream, an HTTP request, etc). If you exit the program on error, this does work in some cases like command-line utilities, but your users would not be happy if your GUI app crashes when you open a malformed file.
- gilbetron 4y agoI'm not arguing for or against this approach, merely responding to a question with a factual answer. But since you brought it up ;) I bounce back and forth between which approach I like. Sometimes exceptions seem bulky and unwieldy and honestly a bit lazy. Returning an error feels verbose and annoying and bulky as well. But it also feels like returning an error forces you to think about what should happen, where exceptions let you kick the can down the road. Neither are great, but I find that code that uses exceptions ends up being poorer in design and functioning, but also errors-on-return tends to be harder to read.
- noobermin 4y agoThis is fine, this is exception handling which you are describing. What exceptions should not be for is handling normal control flow. That is what branches are for. That is what the article is about and what people replying are complaining about.
- knorker 4y agoEntire books, I'm sure, have been written about the pro and cons of exceptions for error handling. Yes, I called it "idiomatic C++" before, but reasonable people disagree about the best option. Smarter people than me have written good things in the E section of the C++ Core Guidelines. The people involved have overlap with the C++ standards committee: http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#S-errors http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#... At least if you use exceptions for errors C++ doesn't need "finally", because it has working RAII, unlike Java.
- grishka 4y agoIn modern Java, and by modern I mean 8 and newer, you no longer need "finally", there's "try with resources" instead that would close everything upon leaving the try block: try(FileInputStream in=new FileInputStream(file)){ // do something with the file data }catch(IOException x){ x.printStackTrace(); } It's been a very long time since I last wrote "something.close()".