Why use try … finally without a catch clause?

Posted by Nick Rosencrantz on Programmers See other posts from Programmers or by Nick Rosencrantz
Published on 2012-01-23T17:20:46Z Indexed on 2012/09/18 9:51 UTC
Read the original article Hit count: 446

The classical way to program is with try / catch but when is it appropriate to use try without catch? In Python the following appears legal and can make sense:

try:
  #do work
finally:
  #do something unconditional

But we didn't catch anything. Similarly one could think in Java it would be

try {
    //for example try to get a database connection
}
finally {
  //closeConnection(connection)
}

It looks good and suddenly I don't have to worry about exception types etc. But if this is good practice, when is it good practice? Or reasons why this is not good practice or not legal (I didn't compile the source I'm asking about and it could be a syntax error for Java but I checked that the Python surely compiles.)

A related problem I've run into is that I continue writing the function / method and at the end I must return something and I'm in a place which should not be reached and it must be a return point so even if I handle the exceptions above I'm still returning null or an empty string at some point in the code which should not be reached, often the end of the method / function. I've always managed to restructure to code so that I don't have to return null since that absolutely appears to look like less than good practice.

© Programmers or respective owner

Related posts about java

Related posts about python