Linked by Eugenia Loli-Queru on Sun 25th Dec 2005 23:38 UTC
Java There are always exceptions to the rule, right? In Java, those exceptions allow a clean break from normal program flow in the event of an exceptional situation. They're not used for program flow interruption, but for program flow branching, which can sometimes lead to difficult-to-maintain code. Marcus Zarra walks you through several best practices for using exceptions in Java.
Thread beginning with comment 78726
To view parent comment, click here.
To read all comments associated with this story, please click here.
RE[2]: ...
by on Tue 27th Dec 2005 18:39 UTC in reply to "RE: ..."

Member since:

> Can you describe, what's wrong with C++ exceptions? And why Java exceptions are unproblematic compared to them?

Nested exceptions? A nightmare. For example,

class A {
public:
A() { ... }
~A() { if (C1) throw E1; }
...
}

void foo()
{
A a;
...
if (C2)
throw E2;
}

if condition C2 is true, then exception E2 is thrown, and this causes A's destructor to be called while the excepting is "unwinding" the call stack. If condition C1 in A's destructor is also true, then... KABOOM!!! Your application dies hard :-)

There's a large C++ application written (by someone else at my company) with these pitfalls. It has been a nightmare to fix these issues.

Regards,
Carlos

Reply Parent Bookmark Score: 0

RE[3]: ...
by luser on Tue 27th Dec 2005 22:13 in reply to "RE[2]: ..."
luser Member since:
2005-08-31

It's your coworker fault, and actually C++ notifying you that programming error is a feature ;) . Throwing exceptions in a C++ destructor it's generally a bad programming practice (exceptions thrown in Java finalizers are simply ignored, that should give you an idea).

http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.3

OTOH, throwing E1 in a finally block during stack unwinding, will swallow E2 silently. You'll end up handling (or maybe ignoring) an exception that it's not the cause your code doesn't work.

public class Main {
void doSomething() throws Exception {
throw new Exception("i know why it does not work");
}
void throwIt() {
throw new RuntimeException("i have no idea why it does not work");
}
void run() throws Exception {
try {
doSomething();
} finally {
throwIt();
}
}
public static void main(String[] args) throws Exception {
new Main().run();
}
}

C++ job is far better pointing you bad exception handling than Java.

Reply Parent Bookmark Score: 1