Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue after try-catch-finally

This might sound like a weird question but I don't get it...

Let's say I have an application which connects to a server to do some stuff. This connect might fail and throw an exception which I can catch.

try {
  Client.connect();
} catch (System.Exception ex) {
  // Do some exception handling...
} finally {
  // Do some cleanup...
}

However, in case that the connect is succcesful the application shall continue...

try {
  Client.connect();
} catch (System.Exception ex) {
  // Do some exception handling...
} finally {
  // Do some cleanup...
}

// Talk to the server...

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?

like image 545
Robert Strauch Avatar asked Jun 06 '12 20:06

Robert Strauch


1 Answers

"Talk to the server" should happen in the try block, right after

Client.connect();
like image 166
Eric J. Avatar answered Sep 28 '22 10:09

Eric J.