tags:

views:

601

answers:

8

I am a computer science student therefore I do not know that much.

I was recently talking with a friend who just got a job as a (java) software developer. He told me that in his job there is a guy who is really experienced in C++, but unfortunately every time he writes code in java, he is using the try-catch to control the flow of the program. According to my friend this is a wrong style in Java. Is this true? What are the differences (if any) in using try-catch(-finally in java) between C++ and Java?

+26  A: 

Using try-catch to control the flow of the program is wrong anywhere... Exception handling is what it says it is: Handling of exceptional circumstances.

Of course for every rule there are a dozen counter-examples of necessary deviations, but generally speaking: Don't control program flow with exceptions.

Using exceptions for controlling the flow of a program occurs when you anticipate certain exceptions being thrown in a normal operating environment, and you make logical decisions based on those exceptions.

For example controlling program flow in pseudo code:

try {
  write update to file
} catch (IOException) {
  write update to alternate file
}

In this case it would be better to actually test for path existence before blindly performing the write.

I removed the permission checking notes because it's a bad example

A good usage of exception handling: (pseudo code again)

try {
  do stuff
} catch(OutOfMemoryException) {
  fail gracefully (don't try and do something else to achieve the same result)
}
John Weldon
Hi. Thanks for answer. Would it be possible please to show some code where a try-catch is controlling the flow, and a similar case where it does not ? Thanks
Muggen
That's a really good question @Muggen; I'll give it a shot in updating my answer, but I think that's worth a question of it's own.
John Weldon
@Muggen if you have an open file you should be able to read, but if you can't this an exceptional case. If an user tries to login but input an invalid password this is a normal flow condition and should be treated like this, not with try-catch
Daniel Moura
Good example @Daniel
John Weldon
Nice edit. So from what understand, not just from this post, is that try-catch should not be used all the time but only in "brutal" cases ? cheers
Muggen
@Muggen; another way of saying it is: if you can think of a scenario likely to occur in the normal flow of use, you probably don't want to use exceptions to handle that. (With all the caveats about general answers that go with that)
John Weldon
This is a good answer, but I'd like to comment on the "permissions checking" example - trying to check permissions yourself before performing an operation is often *not* a good design choice. Generally, you should just try the operation and handle the failure. That's because checking permissions can be very complex, and it can be very difficult to match the checks that the system might perform. Simpler examples might be of checking for a null reference before using it instead of catching a NullPointerException or determining an array's size instead of catching on IndexOutOfBoundsException.
Michael Burr
@Michael: You're correct, because it's a race condition. You could have full permissions to a file, but then lose them. Or you could still have them, but some other process opens the file with sharing disabled. If you genuinely can't predict failure, you have no choice but to react to it with selective catching.
Steven Sudit
@Michael: In fact, I'm not sure your proposed examples are much better. If a variable is unexpectedly null, what exactly are you going to do about it? Throw an exception anyhow? There are some advantages to checking, in that you could throw a better exception, or you could throw now instead of passing a null to another method. Having said that, if it's truly exceptional, it may make sense to just let it throw.
Steven Sudit
@Steven: exactly - but remember that this question is about explicit flow of control handling - which implies that for the purposes of this topic, the null reference would be an expected situation (ie., the code flow will do something useful/documented because of it). If a null reference/pointer is going to cause you to change what your code does (a default action or return a non-exception error result), then an explicit test should be done. That work shouldn't be done by catching the NullPointerException.
Michael Burr
At least in Python, the Exception is the way to go at your example for the reasons Michael pointed out."Easier to ask forgiveness than permission"
Juri Robl
I just downvoted this answer and offered my own.
Steven Sudit
@Juri: Python is very different in this regard from C++, Java and C#.
Steven Sudit
@Michael: If I get an unexpected `NullReferenceException`, there are still some reasonable things I can do, such as rethrow it as the inner exception of `MyEndUserReadableException`, with a message along the lines of "General failure. Please contact technical support at (800) 555-1212." Likewise, I might log the error and return `false`. Do these count as *inappropriate* flow control using exceptions?
Steven Sudit
@Michael thanks for the note about permission checking; it was just an example I thought of when trying to provide sample code... good info.
John Weldon
@Stephen: I don't think I'm disagreeing with you (but maybe I'm reading past something). If you're going to do the things you describe they should probably be handled at a high level in the stack (catching a general exception, not that there's a problem with some particular reference variable in that particular method). If you expect that `someRef = GetAnItem()` might return a null reference, and you want to do something particular when `someRef` is `null`, that's probably best handled by an `if (someRef == null)` instead of catching an exception when executing `someRef.DoSomething()`.
Michael Burr
@Michael; did you intend to reply to @Steven rather than @Stephen?
John Weldon
Yes - sorry for the careless typo, Steven.
Michael Burr
@Michael: I'm also not sure that we're disagreeing, though we do seem to be emphasizing different aspects. Let me give you a real example. I have a program that has to attempt to perform a task against a list of items. If it fails on one item, even for inexplicable (exceptional!) reasons, it *must* not stop. It is required to at least *attempt* the other items. In this case, I want my catch-all to be in `ProcessItem`, not some higher-level method.
Steven Sudit
A: 

Your question is too vague without sample code. There is no finally in C++.

EDIT In general, you don't want to use exceptions as a means to control the flow. Exceptions are supposed to be used only for exceptional (unexpected situations) cases.

fastcodejava
Actually this answer begins to address the 'other' question the OP posed: What are the differences in exception handling between java and C++
John Weldon
That's a good answer, +1.
fastcodejava
+8  A: 

I would say that from a program architecture point of view the purpose of exceptions is the same in Java and C++. They should be used to handle exceptional cases, not the direct the normal flow of the program.

The most common argument against use of exceptions is that they are slow. Like most arguments based on code speed it's almost always irrelevant nowadays, especially when exceptions are used properly.

James Gaunt
Hi. "...especially when exceptions are used properly.". How can an exception be used improperly ?
Muggen
Whenever it is used to control the flow of the program, rather than handle exceptional cases. For example, if you can check the length of an array, don't use an index out of bounds exception to know you are passed the length of the array for the index, but instead simply have the for loop terminate at the appropriate point.
aperkins
In this case "they are slow" is sort of a proxy argument for "that isn't what they are for". Some people don't grok higher-level symbolic reasoning like this very well, so you have to give them examples. When you use things way outside of their range of intended uses, you get problems (being slow for that use being an example of one). If someone happens to fix the slowness, all still isn't right with the world.
T.E.D.
The key term here is "normal". All exceptions control the flow.
Steven Sudit
+4  A: 

I would expect the C++ and Java worlds to be largely similar in their views:

  1. flow control with try/catch blocks isn't immediately obvious
  2. it's expensive performance-wise. In practise this may not be an issue, but in many scenarios (e.g. tight loops) it will certainly impact you.
Brian Agnew
+6  A: 

I think what he is saying is that he's using exceptions for non-exceptional conditions like normal loop terminations. That is considered a no-no by programmers in most languages that provide exceptions, including C++.

The reason for this is that exceptions tend to drag a fair bit of information along with them. On some platforms, they bring the entire callstack at the point of the exception, for the purposes of displaying it in a nice debug message. That's very expensive, if all you really want is a unconditional control jump.

Instead, you should be using statements like break, return, or even (in a real pinch) goto.

T.E.D.
On the other hand, this is a "yes-yes" in Python where **every for loop** is terminated by handling a StopIteration exception. ;)
UncleBens
@UncleBens - Thank you so much for validating my wishy-washyness. I figured there had to be at least one out there. :-)
T.E.D.
+2  A: 

The try-catch block is intended to do the same thing in all languages- exceptions are one of the many ways of recovering when something goes wrong. In java, the following two statements are identical:

if(x != null){
  //do the normal thing
}
else{
  //recover from the error
}

and

try{
  //do the normal thing
}
catch(NullPointerException ex){
  //recover
}

However, using exceptions is never good idea for a number of reasons:

  • the cost associated with throwing the exception (ie generating a Throwable in Java)
  • the flow of control is not immediately obvious- for instance, if a NullPointerException can be thrown by multiple statements in the try block, how can you tell which one threw it in the catch block
  • etc, etc
reseter
Hi. Thanks for answer. "how can you tell which one threw it in the catch block" is another question I had. So you pretty much suggest that try-catch should only be used in special cases or I understood wrong ? Cheers
Muggen
Be careful when saying those constructs are identical or equivalent. If "// do the normal thing" first does something that doesn't improperly use the `null` reference, then the 2nd example will do some work (possibly with visible side-effects) that won't occur in the 1st example.
Michael Burr
Wait, it's "never" a good idea?! Exceptions are ideal for what they're designed for: exceptions. Unlike result codes, they cannot be ignored, and they automatically bubble up until they find code that's willing to handle them. Never say never, especially about things with a well-defined use.
Steven Sudit
And, yes, I did downvote you.
Steven Sudit
You;ve got a point there, I should've been more precise with my use of never. What I meant is "most people would agree it is generally nota good idea to use exceptions as an alternative to an if-statement. However, most people would agree exceptions are good for handling exceptional circumstances. Please bear in mind they are not the only way"
reseter
+3  A: 

The sole purpose of try/catch is flow control. It is intended to allow us to break out of any loop, and even go past the caller and up to a higher-level function.

However, it's designed for exceptional conditions, such as null references being used, division overflowing or file I/O failing. These are errors that prevent the program from continuing on and must be handled. Generally, they are hard to predict or are very rare.

When an exceptional condition arises, the very best thing to do is to alter the flow of control so that the exception is thrown as far up as it has to be in order to find a catch block willing to handle it. Any method in between gets aborted and unwound, even if it has no code to check for results.

When people complain about using try/catch for flow control, what they should mean is that it's not for flow control in non-exceptional conditions. If all you want to do is exit a loop, use break or return; don't throw an exception and then catch it. That's not what exceptions are for, nor is it what they're good for.

Steven Sudit
Good explanation @Steven. I'm not sure it was worth downvoting my answer, but good nonetheless :)
John Weldon
@John: You got 20 upvotes. The one downvote will at least get people to stop and look at alternatives.
Steven Sudit
+1  A: 

What he may be wanting is multiple ways to not execute a bit of code... so rather than (in java)

if (cond1) {
  some_code();
  if (cond2) {
    some_more_code();
    if (condN) {
      ad_infinitum
    }
  }
}

This can be 'flattened' by throwing some garbage...

try {
  if (!cond1) throw new Throwable();
  some_code();
  if (!cond2) throw new Throwable();
  some_more_code();
  if (!condN) throw new Throwable();
  ad_infinitum();
} catch (Throwable ignore) { }

The problem is what if some real exception was thrown? I think what your colleague should write if he wants to flatten the indentation is something like this:

do {
  if (!cond1) break;
  some_code();
  if (!cond2) break;
  some_more_code();
  if (!condN) break;
  ad_infinitum();
} while (false);

Since do/while always executes we can use the break to approximate a goto (as long as it all goes to the same spot).

shemnon