Why use the “finally” keyword?Why is try {…} finally {…} good; try {…} catch{} bad?Do try/catch...
Are the named pipe created by `mknod` and the FIFO created by `mkfifo` equivalent?
Why didn’t Christianity spread southwards from Ethiopia in the Middle Ages?
Does Dispel Magic destroy Artificer Turrets?
If an arcane trickster rogue uses his mage hand and makes it invisible, does that mean anything the hand picks up is also invisible?
(3 of 11: Akari) What is Pyramid Cult's Favorite Car?
Incrementing add under condition in pandas
Desktop app status bar: Notification vs error message
Is it safe if the neutral lead is exposed and disconnected?
What is the most efficient way to write 'for' loops in Matlab?
Why did Windows 95 crash the whole system but newer Windows only crashed programs?
Summoning A Technology Based Demon
Does Wolfram Mathworld make a mistake describing a discrete probability distribution with a probability density function?
Japanese reading of an integer
Did Vladimir Lenin have a cat?
What container to use to store developer concentrate?
Finding out if upgrading to a newer macOS version will cause issues?
Self-deportation of American Citizens from US
How many oliphaunts died in all of the Lord of the Rings battles?
Exploiting the delay when a festival ticket is scanned
Will this creature from Curse of Strahd reappear after being banished?
Why did some Apollo missions carry a grenade launcher?
Is there a way to know the composition of a Team GO Rocket before going into the fight?
To find islands of 1 and 0 in matrix
Is it possible to attain stream-entry if one is only following "the 5 precepts"?
Why use the “finally” keyword?
Why is try {…} finally {…} good; try {…} catch{} bad?Do try/catch blocks hurt performance when exceptions are not thrown?Reference — What does this symbol mean in PHP?Throwing exceptions in a PHP Try Catch blockWhy shouldn't I use mysql_* functions in PHP?How to capture no file for fs.readFileSync()?What is the benefit to use “finally” after try-catch block in java?PHP parse/syntax errors; and how to solve them?Finally block executing before catchHow is the keyword 'finally' meant to be used in PHP?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}
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.
php error-handling try-catch
|
show 2 more comments
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.
php error-handling try-catch
3
Finally will always be executed, if exception was thrown or not. This is often used for clean-up tasks like unlocking files or what the compiler (PHP) does not do itself.
– Markus Zeller
8 hours ago
2
As @MarkusZeller states, it's commonly used for cleanup. Checkout the java docs for a good detail: docs.oracle.com/javase/tutorial/essential/exceptions/…
– briansol
8 hours ago
1
@MarkusZeller php is interpreted, not compiled.
– bassxzero
8 hours ago
3
If you throw an exception that isn't handled by any of the catch clauses or if you throw an exception from within any of the handlers, then the code following the catch clauses will never be executed, while a finally block will get executed before the exception is further propagated down the call stack
– foobar
8 hours ago
1
@bassxzero Yes, the (PHP) code is interpreted, but in the end it is compiled to bytecode. That does not change the finally behavior.
– Markus Zeller
8 hours ago
|
show 2 more comments
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.
php error-handling try-catch
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.
php error-handling try-catch
php error-handling try-catch
edited 7 hours ago
Kaii
16.2k2 gold badges31 silver badges52 bronze badges
16.2k2 gold badges31 silver badges52 bronze badges
asked 8 hours ago
JakeJake
2,4001 gold badge5 silver badges8 bronze badges
2,4001 gold badge5 silver badges8 bronze badges
3
Finally will always be executed, if exception was thrown or not. This is often used for clean-up tasks like unlocking files or what the compiler (PHP) does not do itself.
– Markus Zeller
8 hours ago
2
As @MarkusZeller states, it's commonly used for cleanup. Checkout the java docs for a good detail: docs.oracle.com/javase/tutorial/essential/exceptions/…
– briansol
8 hours ago
1
@MarkusZeller php is interpreted, not compiled.
– bassxzero
8 hours ago
3
If you throw an exception that isn't handled by any of the catch clauses or if you throw an exception from within any of the handlers, then the code following the catch clauses will never be executed, while a finally block will get executed before the exception is further propagated down the call stack
– foobar
8 hours ago
1
@bassxzero Yes, the (PHP) code is interpreted, but in the end it is compiled to bytecode. That does not change the finally behavior.
– Markus Zeller
8 hours ago
|
show 2 more comments
3
Finally will always be executed, if exception was thrown or not. This is often used for clean-up tasks like unlocking files or what the compiler (PHP) does not do itself.
– Markus Zeller
8 hours ago
2
As @MarkusZeller states, it's commonly used for cleanup. Checkout the java docs for a good detail: docs.oracle.com/javase/tutorial/essential/exceptions/…
– briansol
8 hours ago
1
@MarkusZeller php is interpreted, not compiled.
– bassxzero
8 hours ago
3
If you throw an exception that isn't handled by any of the catch clauses or if you throw an exception from within any of the handlers, then the code following the catch clauses will never be executed, while a finally block will get executed before the exception is further propagated down the call stack
– foobar
8 hours ago
1
@bassxzero Yes, the (PHP) code is interpreted, but in the end it is compiled to bytecode. That does not change the finally behavior.
– Markus Zeller
8 hours ago
3
3
Finally will always be executed, if exception was thrown or not. This is often used for clean-up tasks like unlocking files or what the compiler (PHP) does not do itself.
– Markus Zeller
8 hours ago
Finally will always be executed, if exception was thrown or not. This is often used for clean-up tasks like unlocking files or what the compiler (PHP) does not do itself.
– Markus Zeller
8 hours ago
2
2
As @MarkusZeller states, it's commonly used for cleanup. Checkout the java docs for a good detail: docs.oracle.com/javase/tutorial/essential/exceptions/…
– briansol
8 hours ago
As @MarkusZeller states, it's commonly used for cleanup. Checkout the java docs for a good detail: docs.oracle.com/javase/tutorial/essential/exceptions/…
– briansol
8 hours ago
1
1
@MarkusZeller php is interpreted, not compiled.
– bassxzero
8 hours ago
@MarkusZeller php is interpreted, not compiled.
– bassxzero
8 hours ago
3
3
If you throw an exception that isn't handled by any of the catch clauses or if you throw an exception from within any of the handlers, then the code following the catch clauses will never be executed, while a finally block will get executed before the exception is further propagated down the call stack
– foobar
8 hours ago
If you throw an exception that isn't handled by any of the catch clauses or if you throw an exception from within any of the handlers, then the code following the catch clauses will never be executed, while a finally block will get executed before the exception is further propagated down the call stack
– foobar
8 hours ago
1
1
@bassxzero Yes, the (PHP) code is interpreted, but in the end it is compiled to bytecode. That does not change the finally behavior.
– Markus Zeller
8 hours ago
@bassxzero Yes, the (PHP) code is interpreted, but in the end it is compiled to bytecode. That does not change the finally behavior.
– Markus Zeller
8 hours ago
|
show 2 more comments
3 Answers
3
active
oldest
votes
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 :)
New contributor
Just to make sure I understand what you're conveying, the condition that I'm not seeing is when an error occurs in the catch statement(s); in which case a finally statement can still run despite a new, uncaught error arising? The implication being, that you should in fact use finally statements since you can't always predict errors in catch statements?
– Jake
7 hours ago
1
Although the syntax appears to be Java, this is a good example and explanation.
– adam
6 hours ago
1
Precisely :) Another possible exception for when you might not need a finally block could be if the catch is incredibly simple (like maybeSystem.out.println("uh oh");
but it I usually just prefer being safe to sorry :) @adam thank you and good eye. I am more familiar with Java, but figured that the concept would be the same.
– Reagan Duggins
6 hours ago
add a comment |
finally
is more than syntactic sugar. It's all about the return flow of the call stack.
Besides the differences in the control flow, it is always considered good practise to put the cleanup for whatever you tried in the try
block in a finally
statement to ensure the cleanup is also done when your try fails.
Put together what belongs together. People like clean code.
Here are some things finally
enables you to do, which code below a try/catch cannot:
finally
will always run, even when yourcatch
blows up in a fatal error. The only other ways to achieve this are to implement a global error handler.
finally
helps you to keep the cleanup code in place.
finally { throw new OverrideException(); }
causes PHP to override all exceptions thrown in anothercatch
block with the newly thrown exception in thefinally
branch. Code after the try/catch cannot be reached when you throw a new Exception inside a try/catch block.
finally { return $sth; }
inside a function causes PHP to forget all thrown exceptions in this function. It also overrides the return value from a try/catch block.
Cited from a comment from (php at marcuspope dot com) in the PHP manual:
Using a return statement inside a finally block will override any other return statement or thrown exception from the try block and all defined catch blocks. Code execution in the parent stack will continue as if the exception was never thrown.
Frankly this is a good design decision because it means I can optionally dismiss all thrown exceptions from 1 or more catch blocks in one place, without having to nest my whole try block inside an additional (and otherwise needless) try/catch block.
This is the same behavior as Java, whereas C# throws a compile time error when a return statement exists inside a finally block. So I figured it was worth pointing out to PHP devs who may not have any exposure to finally blocks or how other languages do it.
<?php
function asdf()
{
try {
throw new Exception('error');
}
catch(Exception $e) {
echo "An error occurred";
throw $e;
}
finally {
// This overrides the exception as if it were never thrown
return "nException erased";
}
}
try {
echo asdf();
}
catch(Exception $e) {
echo "nResult: " . $e->getMessage();
}
?>
add a comment |
What's special about a finally {}
block is that it will (almost) always run.
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.) It can even use return
itself, and its return value will override the other block's return value!
The only situation where a finally {}
block won't run is if the entire process is destroyed, e.g. by calling exit()
or die()
.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57260796%2fwhy-use-the-finally-keyword%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
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 :)
New contributor
Just to make sure I understand what you're conveying, the condition that I'm not seeing is when an error occurs in the catch statement(s); in which case a finally statement can still run despite a new, uncaught error arising? The implication being, that you should in fact use finally statements since you can't always predict errors in catch statements?
– Jake
7 hours ago
1
Although the syntax appears to be Java, this is a good example and explanation.
– adam
6 hours ago
1
Precisely :) Another possible exception for when you might not need a finally block could be if the catch is incredibly simple (like maybeSystem.out.println("uh oh");
but it I usually just prefer being safe to sorry :) @adam thank you and good eye. I am more familiar with Java, but figured that the concept would be the same.
– Reagan Duggins
6 hours ago
add a comment |
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 :)
New contributor
Just to make sure I understand what you're conveying, the condition that I'm not seeing is when an error occurs in the catch statement(s); in which case a finally statement can still run despite a new, uncaught error arising? The implication being, that you should in fact use finally statements since you can't always predict errors in catch statements?
– Jake
7 hours ago
1
Although the syntax appears to be Java, this is a good example and explanation.
– adam
6 hours ago
1
Precisely :) Another possible exception for when you might not need a finally block could be if the catch is incredibly simple (like maybeSystem.out.println("uh oh");
but it I usually just prefer being safe to sorry :) @adam thank you and good eye. I am more familiar with Java, but figured that the concept would be the same.
– Reagan Duggins
6 hours ago
add a comment |
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 :)
New contributor
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 :)
New contributor
New contributor
answered 8 hours ago
Reagan DugginsReagan Duggins
462 bronze badges
462 bronze badges
New contributor
New contributor
Just to make sure I understand what you're conveying, the condition that I'm not seeing is when an error occurs in the catch statement(s); in which case a finally statement can still run despite a new, uncaught error arising? The implication being, that you should in fact use finally statements since you can't always predict errors in catch statements?
– Jake
7 hours ago
1
Although the syntax appears to be Java, this is a good example and explanation.
– adam
6 hours ago
1
Precisely :) Another possible exception for when you might not need a finally block could be if the catch is incredibly simple (like maybeSystem.out.println("uh oh");
but it I usually just prefer being safe to sorry :) @adam thank you and good eye. I am more familiar with Java, but figured that the concept would be the same.
– Reagan Duggins
6 hours ago
add a comment |
Just to make sure I understand what you're conveying, the condition that I'm not seeing is when an error occurs in the catch statement(s); in which case a finally statement can still run despite a new, uncaught error arising? The implication being, that you should in fact use finally statements since you can't always predict errors in catch statements?
– Jake
7 hours ago
1
Although the syntax appears to be Java, this is a good example and explanation.
– adam
6 hours ago
1
Precisely :) Another possible exception for when you might not need a finally block could be if the catch is incredibly simple (like maybeSystem.out.println("uh oh");
but it I usually just prefer being safe to sorry :) @adam thank you and good eye. I am more familiar with Java, but figured that the concept would be the same.
– Reagan Duggins
6 hours ago
Just to make sure I understand what you're conveying, the condition that I'm not seeing is when an error occurs in the catch statement(s); in which case a finally statement can still run despite a new, uncaught error arising? The implication being, that you should in fact use finally statements since you can't always predict errors in catch statements?
– Jake
7 hours ago
Just to make sure I understand what you're conveying, the condition that I'm not seeing is when an error occurs in the catch statement(s); in which case a finally statement can still run despite a new, uncaught error arising? The implication being, that you should in fact use finally statements since you can't always predict errors in catch statements?
– Jake
7 hours ago
1
1
Although the syntax appears to be Java, this is a good example and explanation.
– adam
6 hours ago
Although the syntax appears to be Java, this is a good example and explanation.
– adam
6 hours ago
1
1
Precisely :) Another possible exception for when you might not need a finally block could be if the catch is incredibly simple (like maybe
System.out.println("uh oh");
but it I usually just prefer being safe to sorry :) @adam thank you and good eye. I am more familiar with Java, but figured that the concept would be the same.– Reagan Duggins
6 hours ago
Precisely :) Another possible exception for when you might not need a finally block could be if the catch is incredibly simple (like maybe
System.out.println("uh oh");
but it I usually just prefer being safe to sorry :) @adam thank you and good eye. I am more familiar with Java, but figured that the concept would be the same.– Reagan Duggins
6 hours ago
add a comment |
finally
is more than syntactic sugar. It's all about the return flow of the call stack.
Besides the differences in the control flow, it is always considered good practise to put the cleanup for whatever you tried in the try
block in a finally
statement to ensure the cleanup is also done when your try fails.
Put together what belongs together. People like clean code.
Here are some things finally
enables you to do, which code below a try/catch cannot:
finally
will always run, even when yourcatch
blows up in a fatal error. The only other ways to achieve this are to implement a global error handler.
finally
helps you to keep the cleanup code in place.
finally { throw new OverrideException(); }
causes PHP to override all exceptions thrown in anothercatch
block with the newly thrown exception in thefinally
branch. Code after the try/catch cannot be reached when you throw a new Exception inside a try/catch block.
finally { return $sth; }
inside a function causes PHP to forget all thrown exceptions in this function. It also overrides the return value from a try/catch block.
Cited from a comment from (php at marcuspope dot com) in the PHP manual:
Using a return statement inside a finally block will override any other return statement or thrown exception from the try block and all defined catch blocks. Code execution in the parent stack will continue as if the exception was never thrown.
Frankly this is a good design decision because it means I can optionally dismiss all thrown exceptions from 1 or more catch blocks in one place, without having to nest my whole try block inside an additional (and otherwise needless) try/catch block.
This is the same behavior as Java, whereas C# throws a compile time error when a return statement exists inside a finally block. So I figured it was worth pointing out to PHP devs who may not have any exposure to finally blocks or how other languages do it.
<?php
function asdf()
{
try {
throw new Exception('error');
}
catch(Exception $e) {
echo "An error occurred";
throw $e;
}
finally {
// This overrides the exception as if it were never thrown
return "nException erased";
}
}
try {
echo asdf();
}
catch(Exception $e) {
echo "nResult: " . $e->getMessage();
}
?>
add a comment |
finally
is more than syntactic sugar. It's all about the return flow of the call stack.
Besides the differences in the control flow, it is always considered good practise to put the cleanup for whatever you tried in the try
block in a finally
statement to ensure the cleanup is also done when your try fails.
Put together what belongs together. People like clean code.
Here are some things finally
enables you to do, which code below a try/catch cannot:
finally
will always run, even when yourcatch
blows up in a fatal error. The only other ways to achieve this are to implement a global error handler.
finally
helps you to keep the cleanup code in place.
finally { throw new OverrideException(); }
causes PHP to override all exceptions thrown in anothercatch
block with the newly thrown exception in thefinally
branch. Code after the try/catch cannot be reached when you throw a new Exception inside a try/catch block.
finally { return $sth; }
inside a function causes PHP to forget all thrown exceptions in this function. It also overrides the return value from a try/catch block.
Cited from a comment from (php at marcuspope dot com) in the PHP manual:
Using a return statement inside a finally block will override any other return statement or thrown exception from the try block and all defined catch blocks. Code execution in the parent stack will continue as if the exception was never thrown.
Frankly this is a good design decision because it means I can optionally dismiss all thrown exceptions from 1 or more catch blocks in one place, without having to nest my whole try block inside an additional (and otherwise needless) try/catch block.
This is the same behavior as Java, whereas C# throws a compile time error when a return statement exists inside a finally block. So I figured it was worth pointing out to PHP devs who may not have any exposure to finally blocks or how other languages do it.
<?php
function asdf()
{
try {
throw new Exception('error');
}
catch(Exception $e) {
echo "An error occurred";
throw $e;
}
finally {
// This overrides the exception as if it were never thrown
return "nException erased";
}
}
try {
echo asdf();
}
catch(Exception $e) {
echo "nResult: " . $e->getMessage();
}
?>
add a comment |
finally
is more than syntactic sugar. It's all about the return flow of the call stack.
Besides the differences in the control flow, it is always considered good practise to put the cleanup for whatever you tried in the try
block in a finally
statement to ensure the cleanup is also done when your try fails.
Put together what belongs together. People like clean code.
Here are some things finally
enables you to do, which code below a try/catch cannot:
finally
will always run, even when yourcatch
blows up in a fatal error. The only other ways to achieve this are to implement a global error handler.
finally
helps you to keep the cleanup code in place.
finally { throw new OverrideException(); }
causes PHP to override all exceptions thrown in anothercatch
block with the newly thrown exception in thefinally
branch. Code after the try/catch cannot be reached when you throw a new Exception inside a try/catch block.
finally { return $sth; }
inside a function causes PHP to forget all thrown exceptions in this function. It also overrides the return value from a try/catch block.
Cited from a comment from (php at marcuspope dot com) in the PHP manual:
Using a return statement inside a finally block will override any other return statement or thrown exception from the try block and all defined catch blocks. Code execution in the parent stack will continue as if the exception was never thrown.
Frankly this is a good design decision because it means I can optionally dismiss all thrown exceptions from 1 or more catch blocks in one place, without having to nest my whole try block inside an additional (and otherwise needless) try/catch block.
This is the same behavior as Java, whereas C# throws a compile time error when a return statement exists inside a finally block. So I figured it was worth pointing out to PHP devs who may not have any exposure to finally blocks or how other languages do it.
<?php
function asdf()
{
try {
throw new Exception('error');
}
catch(Exception $e) {
echo "An error occurred";
throw $e;
}
finally {
// This overrides the exception as if it were never thrown
return "nException erased";
}
}
try {
echo asdf();
}
catch(Exception $e) {
echo "nResult: " . $e->getMessage();
}
?>
finally
is more than syntactic sugar. It's all about the return flow of the call stack.
Besides the differences in the control flow, it is always considered good practise to put the cleanup for whatever you tried in the try
block in a finally
statement to ensure the cleanup is also done when your try fails.
Put together what belongs together. People like clean code.
Here are some things finally
enables you to do, which code below a try/catch cannot:
finally
will always run, even when yourcatch
blows up in a fatal error. The only other ways to achieve this are to implement a global error handler.
finally
helps you to keep the cleanup code in place.
finally { throw new OverrideException(); }
causes PHP to override all exceptions thrown in anothercatch
block with the newly thrown exception in thefinally
branch. Code after the try/catch cannot be reached when you throw a new Exception inside a try/catch block.
finally { return $sth; }
inside a function causes PHP to forget all thrown exceptions in this function. It also overrides the return value from a try/catch block.
Cited from a comment from (php at marcuspope dot com) in the PHP manual:
Using a return statement inside a finally block will override any other return statement or thrown exception from the try block and all defined catch blocks. Code execution in the parent stack will continue as if the exception was never thrown.
Frankly this is a good design decision because it means I can optionally dismiss all thrown exceptions from 1 or more catch blocks in one place, without having to nest my whole try block inside an additional (and otherwise needless) try/catch block.
This is the same behavior as Java, whereas C# throws a compile time error when a return statement exists inside a finally block. So I figured it was worth pointing out to PHP devs who may not have any exposure to finally blocks or how other languages do it.
<?php
function asdf()
{
try {
throw new Exception('error');
}
catch(Exception $e) {
echo "An error occurred";
throw $e;
}
finally {
// This overrides the exception as if it were never thrown
return "nException erased";
}
}
try {
echo asdf();
}
catch(Exception $e) {
echo "nResult: " . $e->getMessage();
}
?>
edited 6 hours ago
answered 8 hours ago
KaiiKaii
16.2k2 gold badges31 silver badges52 bronze badges
16.2k2 gold badges31 silver badges52 bronze badges
add a comment |
add a comment |
What's special about a finally {}
block is that it will (almost) always run.
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.) It can even use return
itself, and its return value will override the other block's return value!
The only situation where a finally {}
block won't run is if the entire process is destroyed, e.g. by calling exit()
or die()
.
add a comment |
What's special about a finally {}
block is that it will (almost) always run.
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.) It can even use return
itself, and its return value will override the other block's return value!
The only situation where a finally {}
block won't run is if the entire process is destroyed, e.g. by calling exit()
or die()
.
add a comment |
What's special about a finally {}
block is that it will (almost) always run.
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.) It can even use return
itself, and its return value will override the other block's return value!
The only situation where a finally {}
block won't run is if the entire process is destroyed, e.g. by calling exit()
or die()
.
What's special about a finally {}
block is that it will (almost) always run.
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.) It can even use return
itself, and its return value will override the other block's return value!
The only situation where a finally {}
block won't run is if the entire process is destroyed, e.g. by calling exit()
or die()
.
answered 8 hours ago
duskwuffduskwuff
154k20 gold badges192 silver badges243 bronze badges
154k20 gold badges192 silver badges243 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57260796%2fwhy-use-the-finally-keyword%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
Finally will always be executed, if exception was thrown or not. This is often used for clean-up tasks like unlocking files or what the compiler (PHP) does not do itself.
– Markus Zeller
8 hours ago
2
As @MarkusZeller states, it's commonly used for cleanup. Checkout the java docs for a good detail: docs.oracle.com/javase/tutorial/essential/exceptions/…
– briansol
8 hours ago
1
@MarkusZeller php is interpreted, not compiled.
– bassxzero
8 hours ago
3
If you throw an exception that isn't handled by any of the catch clauses or if you throw an exception from within any of the handlers, then the code following the catch clauses will never be executed, while a finally block will get executed before the exception is further propagated down the call stack
– foobar
8 hours ago
1
@bassxzero Yes, the (PHP) code is interpreted, but in the end it is compiled to bytecode. That does not change the finally behavior.
– Markus Zeller
8 hours ago