by mccoyst · 14y ago · 0 comments
try {
...
int rc = fx ();
if (rc != 0)
throw std::exception ("Error!");
...
catch (std::exception &e) {
handle_exception ();
}
Why is he throwing exceptions and catching them within the same function? His "C equivalent" is what he should've been doing in C++."C++ exceptions just didn't fill the bill. They are great for guaranteeing that program doesn't fail — just wrap the main function in try/catch block and you can handle all the errors in a single place."
This is something i learned in my very first computer science lecture not to do.
To be fair: It's what exceptions can be good for - a last barrier before a crash and a way to handle errors later. But you're absolutely right that he simply could react directly to the error. Or throw specific exceptions and react to them. His described issue has nothing to do with exceptions themselves, just with the way he thinks he has to use them.
Memory corruption? Appropriate response: fail. Logic error? Appropriate response: fail. Exception? Appropriate response? Decide if program can continue, respond.
I'd say the bigger issue is less of "exceptions" so much as "states". Adding any kind of error handling increases the number of state conditions that your program may be in, and that complexity is obscenely hard to manage. I don't think C or C++ or Java or Erlang or any other language will free you from the burden of proper software engineering.
Not only that, I don't think C++ exceptions are necessarily very good at being a 'last barrier' before a crash - they simply can't catch all the errors, because they are good at indicating conditions that might be recoverable, not catching and recovering from logic errors that would cause a crash. There are plenty of ways to hang yourself in C++ without ever throwing an exception.
Ah, Java code at my workplace.
catch(Exception e) {}Yes, and he learned not to do it also, thank you.
He makes a tongue in cheek comment about a common Exceptions abuse. Actually, in the very next sentence after than one, he explains why that is bad.
Do people on Hacker News believe that the guy doesn't know C++? He is the frigging author of one of the most useful, used, high quality C++ libs.
No, he doesn't. The very next sentence is:
"However, what's great for avoiding straightforward failures becomes a nightmare when your goal is to guarantee that no undefined behaviour happens."
It's great if your goal is to avoid straightforward failure (= crash), it's bad if your goal is to also avoid undefined behavior (= invalid program state).
Have you discovered something else on the matter?
try {
foo();
catch (std::exception &e) {
handle_exception ();
}
int foo () {
int rc = fx ();
if (rc != 0)
throw std::exception ("Error!");
}