Why use the “finally” keyword? [duplicate]Why do we use finally blocks?Why use finally in C#?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?
Shabbat clothing on shabbat chazon
Word or idiom defining something barely functional
Is it really ~648.69 km/s delta-v to "land" on the surface of the Sun?
Double blind peer review when paper cites author's GitHub repo for code
How can you evade tax by getting employment income just in equity, then using this equity as collateral to take out loan?
Acceptable to cut steak before searing?
Does a code snippet compile? Or does it gets compiled?
What is the best way to cause swarm intelligence to be destroyed?
Infeasibility in mathematical optimization models
Can a character who casts Shapechange and turns into a spellcaster use innate spellcasting to cast spells with a long casting time?
Should I self-publish my novella on Amazon or try my luck getting publishers?
How would a family travel from Indiana to Texas in 1911?
How to display a duet in lyrics?
Dropdowns & Chevrons for Right to Left languages
Reusing story title as chapter title
Do other countries guarantee freedoms that the United States does not have?
Is refreshing multiple times a test case for web applications?
Can a College of Swords bard use Blade Flourishes multiple times in a turn?
Why are physicists so interested in irreps if in their non-block-diagonal form they mix all components of a vector?
How do I calculate the difference in lens reach between a superzoom compact and a DSLR zoom lens?
Sierpinski turtle triangle
How would I as a DM create a smart phone-like spell/device my players could use?
Generator for parity?
Are there any differences in causality between linear and logistic regression?
Why use the “finally” keyword? [duplicate]
Why do we use finally blocks?Why use finally in C#?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;
This question already has an answer here:
Why do we use finally blocks?
10 answers
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
marked as duplicate by John Conde, Alma Do
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Jul 30 at 14:42
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
|
show 3 more comments
This question already has an answer here:
Why do we use finally blocks?
10 answers
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
marked as duplicate by John Conde, Alma Do
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Jul 30 at 14:42
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
10
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
Jul 29 at 20:20
3
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
Jul 29 at 20:21
1
@MarkusZeller php is interpreted, not compiled.
– bassxzero
Jul 29 at 20:23
6
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
Jul 29 at 20:24
2
@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
Jul 29 at 20:30
|
show 3 more comments
This question already has an answer here:
Why do we use finally blocks?
10 answers
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
This question already has an answer here:
Why do we use finally blocks?
10 answers
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.
This question already has an answer here:
Why do we use finally blocks?
10 answers
php error-handling try-catch
php error-handling try-catch
edited Jul 29 at 21:07
Kaii
16.2k2 gold badges31 silver badges54 bronze badges
16.2k2 gold badges31 silver badges54 bronze badges
asked Jul 29 at 20:13
JakeJake
2,4541 gold badge6 silver badges10 bronze badges
2,4541 gold badge6 silver badges10 bronze badges
marked as duplicate by John Conde, Alma Do
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Jul 30 at 14:42
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by John Conde, Alma Do
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Jul 30 at 14:42
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by John Conde, Alma Do
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Jul 30 at 14:42
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
10
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
Jul 29 at 20:20
3
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
Jul 29 at 20:21
1
@MarkusZeller php is interpreted, not compiled.
– bassxzero
Jul 29 at 20:23
6
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
Jul 29 at 20:24
2
@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
Jul 29 at 20:30
|
show 3 more comments
10
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
Jul 29 at 20:20
3
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
Jul 29 at 20:21
1
@MarkusZeller php is interpreted, not compiled.
– bassxzero
Jul 29 at 20:23
6
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
Jul 29 at 20:24
2
@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
Jul 29 at 20:30
10
10
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
Jul 29 at 20:20
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
Jul 29 at 20:20
3
3
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
Jul 29 at 20:21
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
Jul 29 at 20:21
1
1
@MarkusZeller php is interpreted, not compiled.
– bassxzero
Jul 29 at 20:23
@MarkusZeller php is interpreted, not compiled.
– bassxzero
Jul 29 at 20:23
6
6
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
Jul 29 at 20:24
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
Jul 29 at 20:24
2
2
@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
Jul 29 at 20:30
@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
Jul 29 at 20:30
|
show 3 more comments
2 Answers
2
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 :)
1
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
Jul 29 at 21:26
1
Although the syntax appears to be Java, this is a good example and explanation.
– adam
Jul 29 at 21:58
2
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
Jul 29 at 22:34
1
@Jake - Sometimes you also DON'T write catch blocks. Liketry ... finally ...
. Then the exception will get propagated upwards (caught in some other method which can handle it), but thefinally
block will run anyway cleaning up whatever needs to be cleaned up.
– Vilx-
Jul 30 at 11:38
1
@Jake - And at other times, you don't fully handle the exception. Like, you do a little bit in yourcatch
(maybe log it or add some details to the exception object), but then re-throw the exception so that some higher level can catch it and handle it properly. Again,finally
cleans up.
– Vilx-
Jul 30 at 11:39
|
show 1 more comment
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 acatch
. (Thefinally
runs after thecatch
.)It will run if the code in the
try
block throws an exception that wasn't handled by anycatch
block, or if there weren't any at all. (Thefinally
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 thecatch
throws another exception (or rethrows the same exception).It will even run if the code in the
try
block, or in acatch
block, usesreturn
. (Just as with an uncaught exception, thefinally
runs before the function actually returns.) Thefinally
block can even usereturn
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()
.)
To compare and contrast the two snippets in the question, it might be worth mentioning in which of these cases regular code after thetry/catch/finally
would run. (The first two? I'm not sure.)
– ilkkachu
Jul 30 at 12:36
@ilkkachu yes only in the first two.
– Kaii
Jul 30 at 14:12
add a comment |
2 Answers
2
active
oldest
votes
2 Answers
2
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 :)
1
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
Jul 29 at 21:26
1
Although the syntax appears to be Java, this is a good example and explanation.
– adam
Jul 29 at 21:58
2
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
Jul 29 at 22:34
1
@Jake - Sometimes you also DON'T write catch blocks. Liketry ... finally ...
. Then the exception will get propagated upwards (caught in some other method which can handle it), but thefinally
block will run anyway cleaning up whatever needs to be cleaned up.
– Vilx-
Jul 30 at 11:38
1
@Jake - And at other times, you don't fully handle the exception. Like, you do a little bit in yourcatch
(maybe log it or add some details to the exception object), but then re-throw the exception so that some higher level can catch it and handle it properly. Again,finally
cleans up.
– Vilx-
Jul 30 at 11:39
|
show 1 more 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 :)
1
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
Jul 29 at 21:26
1
Although the syntax appears to be Java, this is a good example and explanation.
– adam
Jul 29 at 21:58
2
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
Jul 29 at 22:34
1
@Jake - Sometimes you also DON'T write catch blocks. Liketry ... finally ...
. Then the exception will get propagated upwards (caught in some other method which can handle it), but thefinally
block will run anyway cleaning up whatever needs to be cleaned up.
– Vilx-
Jul 30 at 11:38
1
@Jake - And at other times, you don't fully handle the exception. Like, you do a little bit in yourcatch
(maybe log it or add some details to the exception object), but then re-throw the exception so that some higher level can catch it and handle it properly. Again,finally
cleans up.
– Vilx-
Jul 30 at 11:39
|
show 1 more 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 :)
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 :)
answered Jul 29 at 20:47
Reagan DugginsReagan Duggins
2663 silver badges5 bronze badges
2663 silver badges5 bronze badges
1
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
Jul 29 at 21:26
1
Although the syntax appears to be Java, this is a good example and explanation.
– adam
Jul 29 at 21:58
2
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
Jul 29 at 22:34
1
@Jake - Sometimes you also DON'T write catch blocks. Liketry ... finally ...
. Then the exception will get propagated upwards (caught in some other method which can handle it), but thefinally
block will run anyway cleaning up whatever needs to be cleaned up.
– Vilx-
Jul 30 at 11:38
1
@Jake - And at other times, you don't fully handle the exception. Like, you do a little bit in yourcatch
(maybe log it or add some details to the exception object), but then re-throw the exception so that some higher level can catch it and handle it properly. Again,finally
cleans up.
– Vilx-
Jul 30 at 11:39
|
show 1 more comment
1
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
Jul 29 at 21:26
1
Although the syntax appears to be Java, this is a good example and explanation.
– adam
Jul 29 at 21:58
2
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
Jul 29 at 22:34
1
@Jake - Sometimes you also DON'T write catch blocks. Liketry ... finally ...
. Then the exception will get propagated upwards (caught in some other method which can handle it), but thefinally
block will run anyway cleaning up whatever needs to be cleaned up.
– Vilx-
Jul 30 at 11:38
1
@Jake - And at other times, you don't fully handle the exception. Like, you do a little bit in yourcatch
(maybe log it or add some details to the exception object), but then re-throw the exception so that some higher level can catch it and handle it properly. Again,finally
cleans up.
– Vilx-
Jul 30 at 11:39
1
1
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
Jul 29 at 21:26
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
Jul 29 at 21:26
1
1
Although the syntax appears to be Java, this is a good example and explanation.
– adam
Jul 29 at 21:58
Although the syntax appears to be Java, this is a good example and explanation.
– adam
Jul 29 at 21:58
2
2
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
Jul 29 at 22:34
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
Jul 29 at 22:34
1
1
@Jake - Sometimes you also DON'T write catch blocks. Like
try ... finally ...
. Then the exception will get propagated upwards (caught in some other method which can handle it), but the finally
block will run anyway cleaning up whatever needs to be cleaned up.– Vilx-
Jul 30 at 11:38
@Jake - Sometimes you also DON'T write catch blocks. Like
try ... finally ...
. Then the exception will get propagated upwards (caught in some other method which can handle it), but the finally
block will run anyway cleaning up whatever needs to be cleaned up.– Vilx-
Jul 30 at 11:38
1
1
@Jake - And at other times, you don't fully handle the exception. Like, you do a little bit in your
catch
(maybe log it or add some details to the exception object), but then re-throw the exception so that some higher level can catch it and handle it properly. Again, finally
cleans up.– Vilx-
Jul 30 at 11:39
@Jake - And at other times, you don't fully handle the exception. Like, you do a little bit in your
catch
(maybe log it or add some details to the exception object), but then re-throw the exception so that some higher level can catch it and handle it properly. Again, finally
cleans up.– Vilx-
Jul 30 at 11:39
|
show 1 more comment
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 acatch
. (Thefinally
runs after thecatch
.)It will run if the code in the
try
block throws an exception that wasn't handled by anycatch
block, or if there weren't any at all. (Thefinally
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 thecatch
throws another exception (or rethrows the same exception).It will even run if the code in the
try
block, or in acatch
block, usesreturn
. (Just as with an uncaught exception, thefinally
runs before the function actually returns.) Thefinally
block can even usereturn
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()
.)
To compare and contrast the two snippets in the question, it might be worth mentioning in which of these cases regular code after thetry/catch/finally
would run. (The first two? I'm not sure.)
– ilkkachu
Jul 30 at 12:36
@ilkkachu yes only in the first two.
– Kaii
Jul 30 at 14:12
add a comment |
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 acatch
. (Thefinally
runs after thecatch
.)It will run if the code in the
try
block throws an exception that wasn't handled by anycatch
block, or if there weren't any at all. (Thefinally
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 thecatch
throws another exception (or rethrows the same exception).It will even run if the code in the
try
block, or in acatch
block, usesreturn
. (Just as with an uncaught exception, thefinally
runs before the function actually returns.) Thefinally
block can even usereturn
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()
.)
To compare and contrast the two snippets in the question, it might be worth mentioning in which of these cases regular code after thetry/catch/finally
would run. (The first two? I'm not sure.)
– ilkkachu
Jul 30 at 12:36
@ilkkachu yes only in the first two.
– Kaii
Jul 30 at 14:12
add a comment |
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 acatch
. (Thefinally
runs after thecatch
.)It will run if the code in the
try
block throws an exception that wasn't handled by anycatch
block, or if there weren't any at all. (Thefinally
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 thecatch
throws another exception (or rethrows the same exception).It will even run if the code in the
try
block, or in acatch
block, usesreturn
. (Just as with an uncaught exception, thefinally
runs before the function actually returns.) Thefinally
block can even usereturn
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()
.)
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 acatch
. (Thefinally
runs after thecatch
.)It will run if the code in the
try
block throws an exception that wasn't handled by anycatch
block, or if there weren't any at all. (Thefinally
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 thecatch
throws another exception (or rethrows the same exception).It will even run if the code in the
try
block, or in acatch
block, usesreturn
. (Just as with an uncaught exception, thefinally
runs before the function actually returns.) Thefinally
block can even usereturn
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()
.)
edited Jul 30 at 8:34
Ilmari Karonen
39.1k6 gold badges73 silver badges131 bronze badges
39.1k6 gold badges73 silver badges131 bronze badges
answered Jul 29 at 20:49
duskwuffduskwuff
155k21 gold badges192 silver badges245 bronze badges
155k21 gold badges192 silver badges245 bronze badges
To compare and contrast the two snippets in the question, it might be worth mentioning in which of these cases regular code after thetry/catch/finally
would run. (The first two? I'm not sure.)
– ilkkachu
Jul 30 at 12:36
@ilkkachu yes only in the first two.
– Kaii
Jul 30 at 14:12
add a comment |
To compare and contrast the two snippets in the question, it might be worth mentioning in which of these cases regular code after thetry/catch/finally
would run. (The first two? I'm not sure.)
– ilkkachu
Jul 30 at 12:36
@ilkkachu yes only in the first two.
– Kaii
Jul 30 at 14:12
To compare and contrast the two snippets in the question, it might be worth mentioning in which of these cases regular code after the
try/catch/finally
would run. (The first two? I'm not sure.)– ilkkachu
Jul 30 at 12:36
To compare and contrast the two snippets in the question, it might be worth mentioning in which of these cases regular code after the
try/catch/finally
would run. (The first two? I'm not sure.)– ilkkachu
Jul 30 at 12:36
@ilkkachu yes only in the first two.
– Kaii
Jul 30 at 14:12
@ilkkachu yes only in the first two.
– Kaii
Jul 30 at 14:12
add a comment |
10
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
Jul 29 at 20:20
3
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
Jul 29 at 20:21
1
@MarkusZeller php is interpreted, not compiled.
– bassxzero
Jul 29 at 20:23
6
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
Jul 29 at 20:24
2
@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
Jul 29 at 20:30