Why use the "finally" keyword? [duplicate] - php

This question already has answers here:
Why do we use finally blocks? [duplicate]
(11 answers)
Closed 3 years ago.
I understand what the "finally" keyword is used for in various languages, however, I struggle to understand why you would use it outside of there being a formatting preference in taste.
For instance, in PHP:
try {
possibleErrorThrownFunction();
}
catch (CustomException $customException) {
// handle custom error
}
catch (Exception $exception) {
// handle the error
}
finally {
// run this code every single time regardless of error or not
}
What's the difference between what this code is doing and this?
try {
possibleErrorThrownFunction();
}
catch (CustomException $customException) {
// handle custom error
}
catch (Exception $exception) {
// handle the error
}
// run this code every single time regardless of error or not
Doesn't that last line always get run anyway due to the error being caught? In which case, there is no case to really use finally unless you just want to maintain a code-style formatting?
An example of a case where a finally statement is necessary and distinct from just putting code after try/catch statements would be helpful if I am missing something here.

Short Answer
Finally blocks are guaranteed to run no matter what happens inside of the try and catch blocks, before allowing the program to crash.
This is sort of explained here: https://www.php.net/manual/en/language.exceptions.php though the explanation isn't particularly detailed.
Some More Detail
One example that comes to the top of my head is if you are dealing with input/output streams or something similar that has to be closed after use in order to avoid a memory leak. To use your example:
try {
memoryUser.startReading(someFileOrSomething);
}
catch (CustomException $customException) {
// handle custom error
}
catch (Exception $exception) {
// handle the error
invisibleBug.whoops(); // i.e. something goes wrong in this block
}
memoryUser.Close(); // because something went wrong in the catch block,
// this never runs, which, in this case, causes a memory leak
In this case, wrapping the memoryUser.Close(); in a finally block would ensure that that line would run before the rest of the program exploded, preventing the memory leak even in an otherwise catastrophic failure.
TL;DR
So a lot of the time, people put the finally block there to ensure an important line runs, even if they overlooked something in the catch blocks. This is how I've always seen it used.
Hopefully this helps :)

What's special about a finally {} block is that it will always run at the end of the try {} block.
It will run if the code in the try {} block completes successfully.
It will run if the code in the try {} block throws an exception that was caught by a catch {}. (The finally {} runs after the catch {}.)
It will run if the code in the try {} block throws an exception that wasn't handled by any catch {} block, or if there weren't any at all. (The finally {} block runs before the exception is propagated to the caller.)
It will run if the code in the try {} block throws an exception, and the code in the catch {} throws another exception (or rethrows the same exception).
It will even run if the code in the try {} block, or in a catch {} block, uses return. (Just as with an uncaught exception, the finally {} runs before the function actually returns.) The finally {} block can even use return itself, and its return value will override the value that the other block tried to return!
(There is one edge case where a finally {} block won't run, and that's if the entire process is destroyed, e.g. by being killed, or by calling exit() or die().)

Related

Why can't I catch this error in PHP (calling a function on a boolean)? [duplicate]

This question already has answers here:
PHP try-catch not working
(5 answers)
Closed 4 years ago.
I had an issue that ultimately boiled down to not checking that a value was false before proceeding.
I tried to put a try/catch around it for debugging, but strangely that didn't help.
Here's a minimal example:
try
{
$test = false;
$test->format('Y-m-d');
}
catch (\Exception $e)
{
}
The error log shows that it's a fatal error. Does PHP have documentation on why this wouldn't throw a normal error?
It does trigger "normal" error, but Errors aren't instance of Exception, they are separate branch of objects. Common ancestor for Exception and Error is Throwable and you might want to use that.
Your catch block should look like
catch (\Throwable $e)
{
// do stuff
}
or if you want to catch only Errors
catch (\Error $e)
{
// do stuff
}
Also note that prior to PHP7 Errors and Exceptions are two different things and are handler in different way. Errors can't be caught using try-catch block, you have to use error handler, check set_error_handler

Try {} catch {} on API call or handle differently?

In a Laravel 5.2 app, I'm trying to figure out the most elegant way to handle exceptions when those exceptions are thrown by API calls of external services. These shouldn't stop the program from continuing, because there are other parts of the app that still can be run afterwards that can be done even without the problematic API call.
E.g. currently I have
try {
$statistics->results = $api->call($parameter);
$statistics->status = Statistic::SUCCESS;
} catch (ExternalApiCallException $e) {
$statistics->results = null;
$statistics->status = Statistic::API_CALL_ERROR;
}
I was thinking of using Laravel's app/Exceptions/Handler.php and using
if ($e instanceof ExternalApiCallException $e) {
Log::warning("API Call didn't work");
}
but then I wouldn't be able to set the status of the statistics there, because Handler.php wouldn't have access to it. Is there a better way or are try-catch-blocks the way to go here?
try-catch-finally is definitely a good approach here. In your case API exceptions are localized and should not appear globally (I presume), so I would opt for keeping logic in one place and not putting exception handling as a condition in Handler.php file. In my opinion Handler.php should be used as a last resort option, to style and report otherwise uncaught and unexpected exceptions. For all other cases where exceptions are not critical or even expected, local try {} blocks are easier to maintain, as important parts of the code are not hidden from developer in another file.
Do not forget that you can also use finally {} block, which will be executed after both try{} and catch{} blocks, no matter if the exception was triggered or not.
try
{
// run this first
}
catch (ExternalApiCallException $e)
{
// in case something went wrong
}
finally
{
// this runs after everything else
}

Extended: what's the finally keyword for?

Ok, I understand the "accepted answer" that was given for this question, but it's still not clear to me what kind of code should I put in finally blocks.
If the use of finally is to get the non-catched exceptions thrown and give a general error message for the system not explode for the user, wouldn't appear two error messages for the user if some exception was catched?
[Edit]
Like #MarkBaker said, the "finally" isn't for catch the uncaught exceptions, the generic catch(Exception $e) do that. So... for what it's useful? Or, in other words, what the finally block does that I can't do after the try/catch blocks without finally?
Maybe the following explanation will better help you understand how it works:
try {
function1();//this might throw an exception
function2();//if we want function2 to be executed regardless
//if an exception was thrown from function1() - this
//is not a good place to call it!
} catch (Exception $e) {
echo $e->getMessage();
} finally {
function2();//then the right place to write it will be in a finally clause.
}
When an exception is thrown from function1() - function2() will not be executed - the execution will "jump" to the catch section. If we want function2() to be executed regardless if an error was thrown, for example, if function1() opens a connection to the DB and runs some selects and function2() closes that connection, then we'd better place the call to function2() in the finally block that follows the catch
The 'finally' block should hold code you want executed regardless of the outcome of the try/catch block. For example, if you try to query a database and catch the error, you would still likely want to close the database connection, regardless of whether the database operation succeeded or not. See below:
open_database_conn();
try{
query_database();
return_result();
}
catch(Exception $e){
echo $e->getMessage();
}
finally{
close_database_conn();
}

PHP 5.5 and try ... finally

PHP 5.5 is adding support for finally in try/catch blocks.
Java allows you to create a try/catch/finally block with no catch block, so you can cleanup locally when an exception happens, but let the exception itself propagate up the call stack so it can be dealt with separately.
try {
// Do something that might throw an exception here
} finally {
// Do cleanup and let the exception propagate
}
In current versions of PHP you can achieve something that can do cleanup on an exception and let it propagate, but if no exception is thrown then the cleanup code is never called.
try {
// Do something that might throw an exception here
} catch (Exception $e) {
// Do cleanup and rethrow
throw $e;
}
Will PHP 5.5 support the try/finally style? I have looked for information on this, but the closest I could find to an answer, from PHP.net, only implies that it doesn't.
In PHP 5.5 and later, a finally block may also be specified after the
catch blocks. Code within the finally block will always be executed
after the try and catch blocks, regardless of whether an exception has
been thrown, and before normal execution resumes.
The wording suggests that you're always expected to have a catch block, but it doesn't state it outright as far as I can see.
Yes, try/finally is supported (RFC, live code). The documentation is indeed not very clear and should be amended.
I've implemented a test case on a 5.5RC3 server.
As you can see in the code, it works as expected. Documentation is indeed wrong at this point.

Why should I use exception handling in php?

I've been programming PHP for a long time, but not so much PHP 5... I've known about exception handling in PHP 5 for some time, but never really looked into it. After a quick Google it seems fairly pointless to use exception handling - I can't see the advantages of using it over just using some if() {} statements, and perhaps my own error handling class or whatever.
There's got to be a bunch of good reasons for using it (I guess?!) otherwise it wouldn't have been put into the language (probably). Can anyone tell me of some good benefits it has over just using a bunch of if statements or a switch statement or something?
Exceptions allow you to distinguish between different types of errors, and is also great for routing. For example...
class Application
{
public function run()
{
try {
// Start her up!!
} catch (Exception $e) {
// If Ajax request, send back status and message
if ($this->getRequest()->isAjax()) {
return Application_Json::encode(array(
'status' => 'error',
'msg' => $e->getMessage());
}
// ...otherwise, just throw error
throw $e;
}
}
}
The thrown exception can then be handled by a custom error handler.
Since PHP is a loosely typed language, you might need to ensure that only strings are passed as arguments to a class method. For example...
class StringsOnly
{
public function onlyPassStringToThisMethod($string)
{
if (!is_string($string)) {
throw new InvalidArgumentException('$string is definitely not a string');
}
// Cool string manipulation...
return $this;
}
}
...or if you need to handle different types of exceptions in different ways.
class DifferentExceptionsForDifferentFolks
{
public function catchMeIfYouCan()
{
try {
$this->flyForFree();
} catch (CantFlyForFreeException $e) {
$this->alertAuthorities();
return 'Sorry, you can\'t fly for free dude. It just don\'t work that way!';
} catch (DbException $e) {
// Get DB debug info
$this->logDbDebugInfo();
return 'Could not access database. What did you mess up this time?';
} catch (Exception $e) {
$this->logMiscException($e);
return 'I catch all exceptions for which you did not account!';
}
}
}
If using transactions in something like Zend Framework:
class CreditCardController extends Zend_Controller_Action
{
public function buyforgirlfriendAction()
{
try {
$this->getDb()->beginTransaction();
$this->insertGift($giftName, $giftPrice, $giftWowFactor);
$this->getDb()->commit();
} catch (Exception $e) {
// Error encountered, rollback changes
$this->getDb()->rollBack();
// Re-throw exception, allow ErrorController forward
throw $e;
}
}
}
Exception handling: If condition versus Exception isn't specific to PHP, but gives a good perspective. Personally, Exception(s) & try/catch are implemented in languages to enforce good behaviour amongst developers that normally wouldn't be as attentive to error checking / handling.
If you are confident that your if/else if/else is catching all scenarios, than cool.
Here is an overview of the Advantages of Exceptions - Java -- At one point, there is a snippet of code that has many if/else statements and the following excerpt:
There's so much error detection, reporting, and returning here that the original seven lines of code are lost in the clutter. Worse yet, the logical flow of the code has also been lost, thus making it difficult to tell whether the code is doing the right thing: Is the file really being closed if the function fails to allocate enough memory? It's even more difficult to ensure that the code continues to do the right thing when you modify the method three months after writing it. Many programmers solve this problem by simply ignoring it — errors are reported when their programs crash.
So really, it comes down to personal preference in the end. If you want code that is readable and can be consumed by other people, it's generally a better approach and enforces best-behaviour
If you are following the object-oriented methodology then exceptions comes handy for the error handling. It is convenient to communicate the errors through exception across the objects.
Exceptions are really helpful if you go with layered design approach.
If you are not coding in object-oriented way, then exceptions are not required.
We use exception handling if we are not sure about the code results. We put that snippet of code in try block and catch that error in catch block. Please check this link for more information.
In general there are two good reasons to use exception handling:
You might now always know where an exception will occur - something unexpected could arise. If you use a global exception handler you can make sure that no matter what goes wrong, your program has a chance to recover. Similarly a particularly sensitive piece of code (like something that does I/O) could have all sorts of different errors that can only be detected at runtime and you want to catch any possible contingency. Some things might not occur during testing; like what if a server outside of your control fails? This may never be tested before it really happens (although good testing would include this). This is the more important reason really.
Performance. Typically exceptions are implemented so that everything is fast so long as nothing goes wrong. Exceptions are caught after they occur. This means that no 'if' statement has to be evaluated in advance if something goes wrong, and the overhead is very low in that case. If you don't use exceptions you will be forced to add a lot of 'if' statements to your code. While usually this isn't much of a problem, this can kill a performance-critical application. This is especially true because a branch mis-prediction in the CPU can cause a pipeline flush.
I that reason is that Exception is called after trigger_error(); function and you can send also some additional information to that exception = better debugging?
I'm not sure but I think that's it
example:
class db
{
function connect()
{
mysql_Connect("lolcalhost", "root", "pass:)") or trigger_error("Test");
}
}
try
{
}
catch (db
One of the primary reasons for having an exceptions framework is so that if the code ever gets to the point where it cannot proceed, it has the ability to tell the surrounding context that something has gone wrong. It means that if I have a class Foo which needs to have $fooInstance->setBarHandler($barHandler) called before $fooInstance->doFoo(); can succeed, the class can provide a message to the greater context instead of failing silently and returning FALSE. Further, it allows the context to say, "Huh. That broke. Well, I can now tell the user/logs/something else that something bad happened, and I can decide whether I need to keep on chugging."
Exceptions can provide much more data than simple -1 or false.
Exceptions can do advanced error handling. Keep in mind that try .. catch blocks can be nested and there could be more than one catch block in try .. catch block.
Exceptions force you to handle errors. When you're not using them you do something like:
function doSomething($a, $b, $c) {
...
if ($a < $b && $b > $c) {
return -1; // error
}
...
}
$d = doSomething($x, $y, $z);
if ($d === -1) {
die('Fatal error!');
}
And everything is fine as long as you remember to check whether function returned error. But what happen if you forgot to check that? It's actually a quite common problem.
Exceptions make the flow of a program much more natural.
Exceptions are hard to use in the correct context,especially in php. Personally i use exceptions when these 3 things happen:
Resource failure exception - You can throw an exception maybe when your program runs out of memory. for example in php when you run a script that exceeds 30 seconds executing. Though you can chanage that in .ini
Client code errors exceptions - For example when trying to connect to a database with the wrong credentials or unlinking a file not on server. Or when the database server is down and unresponsive, you can throw an exception.
Programmer error exception - These are errors generated due to your own coding problems.This can also be used when you are not sure of the results your code will give you. for example when dividing by 0.

Categories