The "server talking" however is executed in any case. It doesn't matter if the exception occured or not.

How can I make sure that the "server talking" is only executed if the connect was successful? Do I have to move all of the following code inside the trystatement? What is a clean way to program such a behavior?

It all depends on what you're trying to accomplish. In some cases it may make sense to return in the catch block, particularly if the method returns a status. If the try block is in a loop, you may simply wish to continue to the next iteration in the catch. Though it may be a suprise to the people who brought you ERROR_SUCCESS, not every exception is a failure.
–
HABOJun 6 '12 at 21:45

5 Answers
5

After thinking a little, this is probably the best option: mainly, it avoids code duplication in every catch block (there could be more than one, of course). Still, I think there refactoring the content of the try to a new method might be a good idea.
–
KobiJun 6 '12 at 21:02

After having read all the answers this answer -in combination with Kobi's comment- seems to be the most robust way to do it. Thanks!
–
RobertJun 6 '12 at 21:07

1

This may or may not be a good choice depending on the use case. There may be cases where you get an exception while "talking to the server", handle the exception and continue on talking. If you wrap it in the same try-catch as the one used for Connect, you pretty much have to clean up and leave as soon as you receive one exception. Again, it depends on the use case, but I generally prefer multiple try-catch blocks rather than a single one that wraps everything.
–
Eren ErsönmezJun 6 '12 at 21:16

@Eren: In this case I would argue for a nested try block rather than serial ones, but as you say, depends on the exact use case.
–
Eric J.Jun 6 '12 at 21:24

Why move this outside of the try block? What if another exception happens in your if block that requires finally to execute?
–
Eric J.Jun 6 '12 at 20:56

1

@EricJ. - certainly, there are any number of things that could happen, I was just going by his initial design. Obviously, there may be many other things to consider. Or maybe not.
–
Erik FunkenbuschJun 6 '12 at 20:58

Typically you use try...catch statements for those statements which you expect to throw an Exception. Try...Catch defines its own scope, so you should declare any variables outside of the Try...Catch block (at least, those variables that you want to use outside of it).

If you want to know if an exception was thrown, then define the Exception variable above the Try...Catch. You can then examine it to determine if it is Null or not.