Can I use try-catch-finally like this?

Kamil picture Kamil · Feb 22, 2013 · Viewed 28k times · Source

I'm using try-catch for years, but I never learned how and when to use finally, because I never understood the point of finally (I've read bad books)?

I want to ask you about use of finally in my case.

My code example should explain everything:

$s = "";

$c = MyClassForFileHandling::getInstance();

try
{
    $s = $c->get_file_content($path);
}

catch FileNotFoundExeption
{
    $c->create_file($path, "text for new file");
}

finally
{
    $s = $c->get_file_content($path);
}

Is this correct use of finally?

More precise question:

Shall I use finally (in future PHP versions or other languages) for handling "create something if it not exists" operations?

Answer

mika picture mika · Feb 22, 2013

Finally will always be executed, so in this case, it is not its intended purpose, since normal execution would reopen the file a second time. What you intend to do would be achieved in the same (cleaner) way if you do

$s = "";

$c = MyClassForFileHandling::getInstance();

try
{
    $s = $c->get_file_content($path);
}
catch(FileNotFoundExeption $e)
{
    $c->create_file($path, "text for new file");
    $s = $c->get_file_content($path);
}

Then the manual says:

For the benefit of someone anyone who hasn't come across finally blocks before, the key difference between them and normal code following a try/catch block is that they will be executed even the try/catch block would return control to the calling function.

It might do this if:

  • code if your try block contains an exception type that you don't catch
  • you throw another exception in your catch block
  • your try or catch block calls return

Finally would then be useful in this kind of scenario:

function my_get_file_content($path)
{
    try
    {
        return $c->get_file_content($path);
    }
    catch(FileNotFoundExeption $e)
    {
        $c->create_file($path, "text for new file");
        return $c->get_file_content($path);
    }
    finally
    {
        $c->close_file_handler();
    }
}

=> if you need to make sure you close your file handler in this case, or some resource in general.