They differ if
- the
try-block completes by throwing ajava.lang.Throwablethat is not ajava.lang.Exception, for instance because it is ajava.lang.Errorsuch asAssertionErrororOutOfMemoryError. - the try-block completes abruptly using a control flow statement such a
continue,breakorreturn - the catch-block completes abruptly (by throwing any throwable, or using a control flow statement)
More generally, the java language guarantees that a finally block is executed before the try-statement completes. (Note that if the try-statement does not complete, there is no guarantee about the finally. A statement might not complete for a variety of reasons, including hardware shutdown, OS shutdown, VM shutdown (for instance due to System.exit), the thread waiting (Thread.suspend(), synchronized, Object.wait(), Thread.sleep()) or being otherwise busy (endless loops, ,,,).
So, a finally block is a better place for clean-up actions than the end of the method body, but in itself, still can not guarantee cleanup exeuction.
Videos
What is the purpose of the 'finally' block in Java exception handling?
When is the 'finally' block executed in a Java program?
Can a 'finally' block modify the return value of a method in Java?
They differ if
- the
try-block completes by throwing ajava.lang.Throwablethat is not ajava.lang.Exception, for instance because it is ajava.lang.Errorsuch asAssertionErrororOutOfMemoryError. - the try-block completes abruptly using a control flow statement such a
continue,breakorreturn - the catch-block completes abruptly (by throwing any throwable, or using a control flow statement)
More generally, the java language guarantees that a finally block is executed before the try-statement completes. (Note that if the try-statement does not complete, there is no guarantee about the finally. A statement might not complete for a variety of reasons, including hardware shutdown, OS shutdown, VM shutdown (for instance due to System.exit), the thread waiting (Thread.suspend(), synchronized, Object.wait(), Thread.sleep()) or being otherwise busy (endless loops, ,,,).
So, a finally block is a better place for clean-up actions than the end of the method body, but in itself, still can not guarantee cleanup exeuction.
finally block executes always.
finally block is used for cleanup, like to free resources used within try/catch, close db connections, close sockets, etc.. even when an unhandled exception occurs within your try/catch block.
The only time the finally block doesn't execute is whensystem.exit() is called in try/catch or some error occurs instead of an exception.
The error in the description above means when Java application exit with conditions like Out Of Memory error. I see some downvotes :( for this reason it seems.
final
final can be used to mark a variable "unchangeable"
private final String name = "foo"; //the reference name can never change
final can also make a method not "overrideable"
public final String toString() { return "NULL"; }
final can also make a class not "inheritable". i.e. the class can not be subclassed.
public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed
finally
finally is used in a try/catch statement to execute code "always"
lock.lock();
try {
//do stuff
} catch (SomeException se) {
//handle se
} finally {
lock.unlock(); //always executed, even if Exception or Error or se
}
Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable
finalize
finalize is called when an object is garbage collected. You rarely need to override it. An example:
protected void finalize() {
//free resources (e.g. unallocate memory)
super.finalize();
}
- "Final" denotes that something cannot be changed. You usually want to use this on static variables that will hold the same value throughout the life of your program.
- "Finally" is used in conjunction with a try/catch block. Anything inside of the "finally" clause will be executed regardless of if the code in the 'try' block throws an exception or not.
- "Finalize" is called by the JVM before an object is about to be garbage collected.
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 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 usereturnitself, 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().)